Django Insert Data
Once your models exist, you create new rows either in one step with Model.objects.create(), or by building an instance and calling save().
Two Ways to Insert a Row
Model.objects.create(**fields) builds an instance and saves it in a single call, returning the saved object. Constructing an instance with Model(**fields) and calling .save() separately does the same underlying INSERT, but gives you a chance to inspect or adjust the object first.
Example
from .models import Product
new_product = Product.objects.create(
name='Wireless Mouse',
price=24.99,
in_stock=True,
)
print(new_product.pk) # the new row's primary keyBuilding an Instance First
When you need to set fields conditionally, run some logic, or validate before writing to the database, construct the object first and call .save() once you're ready.
Example
product = Product(name='Mechanical Keyboard', price=89.00)
product.in_stock = True # adjust fields before saving
product.save()Bulk Inserts
bulk_create() inserts a list of unsaved instances in as few queries as possible - much faster than looping and calling save() on each one individually. The tradeoff is that it skips each instance's save() method and any post_save signals.
Example
Product.objects.bulk_create([
Product(name='USB-C Cable', price=9.99),
Product(name='Laptop Stand', price=34.50),
Product(name='Webcam', price=45.00),
])Exercise: Django Insert Data
After creating a model instance in Python, what must you call to write it to the database?