[Django]-Django: Insert row into database

47๐Ÿ‘

โœ…

If you only want to quick test your models you can start an interactive shell and execute your code there.

python manage.py shell

The above command starts a python interactive shell initialized with your Django project settings.

Then you can do something like:

from your_app_name.models import Dodavatel
p = Dodavatel(nazov='Petr', dostupnost=1)
p.save()

I do not recommend to use that code directly inside a view. Instead to create an item I would use a class based view like CreateView.

๐Ÿ‘คLuca

2๐Ÿ‘

For manual inserting data to table for testing purpose

Method1

enter image description here

Execute this command for creating Dodavatel in the database

 python manage.py makemigrations


 python manage.py migrate

enter image description here

Now you can see the table created in the database

enter image description here

Then type for open python project REPL:

python manage.py shell

add this code in the repl

from everych.cheese.models import Dodavatel

 dodavel = Dodavatel.objects.create(nazov="hi", dostupnost=3)

You can use python manage.py shell_plus instead of python manage.py shell.so you didnโ€™t want to add the line from everych. cheese. models import Dodavatel it automatically imported.

here everych my project name

cheese is the application name

change as your project and application name

enter image description here

After the above code is executed data will be inserted into the table
output:-
enter image description here

Method2

Here just inserting data you must add a table using the above step.

python manage.py shell_plus

enter image description here
code

dat = Dodavatel(nazov="Petr", dostupnost=1)
dat.save()

enter image description here
Output:

enter image description here

๐Ÿ‘คlava

Leave a comment