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.
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.
- Adding prefix path to static files in Angular using angular-cli
- Using Django view variables inside templates
- How can I automatically let syncdb add a column (no full migration needed)
- The default "delete selected" admin action in Django
- Difference between self.request and request in Django class-based view
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)
Source:stackexchange.com