[Fixed]-How to insert a row of data to a table using Django's ORM

15👍

If you need to insert a row of data, see the “Saving objects” documentation for the save method on the model.

FYI, you can perform a bulk insert. See the bulk_create method’s documentation.

👤alecxe

12👍

In fact it’s mentioned in the first part of the “Writing your first Django app” tutorial.

As mention in the “Playing with API” section:

>>> from django.utils import timezone
>>> p = Poll(question="What's new?", pub_date=timezone.now())

# Save the object into the database. You have to call save() explicitly.
>>> p.save()

# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> p.id
1

Part-4 of the tutorial explains how to use forms and how to save object using user submitted data.

👤Rohan

7👍

If you don’t want to call the save() method explicitly, you can create a record by using MyModel.objects.create(p1=v1, p2=v1, ...)

fruit = Fruit.objects.create(name='Apple')
# get fruit id
print(fruit.id)

See documentation

Leave a comment