← Back to Django Course | Chapter 4: Models & Django ORM Basics | Lesson 4 of 10

Creating Model Instances

Creating a model instance is like filling out one copy of your form template and saving it into the filing cabinet, which here is the database.

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.

bash
book = Book(title='Django Basics', pages=250)
book.save()
print(book.id)

⚠️ Run this command in your terminal.

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.

Note: Prefer objects.create() when you don't need to change the object before saving.

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.

bash
book = Book.objects.create(title='Learn Django', pages=180)
print(book.id)

⚠️ Run this command in your terminal.

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.

bash
python manage.py shell
>>> from myapp.models import Book
>>> Book.objects.create(title='Shell Demo', pages=90)

⚠️ Run this command in your terminal.

Common Mistakes
  1. Building an object with Model(...) but forgetting to call .save(), so it's never actually written to the database.
  2. Passing a field name that doesn't exist on the model, which raises a TypeError at creation time.
  3. Calling .save() repeatedly inside a loop for bulk data instead of using bulk_create, causing many slow, separate database writes.
Chapter Summary
  • 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.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.