Django: Insert row into database

68,833

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.

Share:
68,833
Milano
Author by

Milano

Updated on July 05, 2022

Comments

  • Milano
    Milano almost 2 years

    I'm new in Django. I've created a table by insert model into models.py.

    Now, I want to insert a row into the database - table Dodavatel. I know, that I have to create an object with attributes as columns. But I don't know where should I put this code. In models.py?

    This is my model:

    class Dodavatel(models.Model):
        nazov = models.CharField(default='', max_length=255)
        dostupnost = models.IntegerField(default=0)
    

    This is the code for inserting a row:

    p = Dodavatel(nazov='Petr', dostupnost=1)
    p.save()
    

    Where should I put this code?