How to use Interactive Console to store data into database

In this tutorial, I will briefly write on how to use the Interactive Console in PyCharm to add data into a database.

Let us use the models below and populate data into the language field using the interactive console in PyCharm :

from django.db import models

# Create your models here.
class Language(models.Model): language_name = models.CharField(max_length=264, unique=True) def __str__(self): return self.top_name class Webpage(models.Model): language = models.ForeignKey(Language, on_delete= models.CASCADE) name = models.CharField(max_length=264, unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class Record(models.Model): name = models.ForeignKey(Webpage,on_delete=models.CASCADE) date = models.DateField() def __str__(self): return str(self.date)

Now let us Add data to Language field

Step 1. use command python manage.py shell
Step 2. Import the class or field to add data into, e.g, from  app_name.models import class_name
Step 3. Create an instance of the class_name, e.g  L = Language(lan_name = "Python")
Step 4. L.save()
Step 5 print(Language.objects.all())

The last step prints what has been saved in the database.

Then type python manage.py runserver, if everything is working fine then you should see the following:

System check identified no issues (0 silenced).
June 11, 20-- - 16:28:01
Django version 3.0.7, using settings 'first_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

However, In order to fully use the database and the Admin, we will need to create a “superuser”

We can do this with the following:
        python manage.py createsuperuser

Then go to the following link, http://127.0.0.1:8000/admin and log in with your superuser details and you should see your data inside the field you have added it to. In our case the Language field.


Watch this.




No comments:

Post a Comment

Note: only a member of this blog may post a comment.

New Post

New style string formatting in Python

In this section, you will learn the usage of the new style formatting. Learn more here . Python 3 introduced a new way to do string formatti...