Creating Model Instances
# Two steps
obj = ModelName(field=value)
obj.save()
# One step
obj = ModelName.objects.create(field=value)
Two-Step Creation
You can build an instance in memory first, then call .save() separately to actually write it to the database.
Example: Two-Step Creation
You can build an instance in memory first, then call .save() separately to actually write it to the database.
book = Book(title='Django Basics', pages=250)
book.save()
print(book.id)
⚠️ Run this in your own terminal or Node.js environment.
One-Step Creation with create()
Model.objects.create(...) builds the instance and saves it to the database in a single call, returning the new object.
Example: One-Step Creation with create()
Model.objects.create(...) builds the instance and saves it to the database in a single call, returning the new object.
book = Book.objects.create(title='Learn Django', pages=180)
print(book.id)
⚠️ Run this in your own terminal or Node.js environment.
Running It in the Django Shell
The Django shell lets you try model creation interactively against your real database, which is useful while learning the ORM.
Example: Running It in the Django Shell
The Django shell lets you try model creation interactively against your real database, which is useful while learning the ORM.
python manage.py shell
>>> from myapp.models import Book
>>> Book.objects.create(title='Shell Demo', pages=90)
⚠️ Run this in your own terminal or Node.js environment.
- Building an object with Model(...) but forgetting to call .save(), so it's never actually written to the database.
- Passing a field name that doesn't exist on the model, which raises a TypeError at creation time.
- Calling .save() repeatedly inside a loop for bulk data instead of using bulk_create, causing many slow, separate database writes.
- You create a new row by instantiating the model class with field values as keyword arguments.
- Calling .save() writes that instance to the database as a new row.
- Model.objects.create(...) does both steps — build and save — in one call.
- Every saved instance automatically gets a unique id from Django.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: