0
0
DjangoHow-ToBeginner · 3 min read

How to Create Object in Django ORM: Simple Guide

To create an object in Django ORM, use the Model.objects.create() method with field values as arguments, or instantiate the model with field values and call save() on it. Both ways add a new record to the database table linked to the model.
📐

Syntax

You can create an object in Django ORM in two main ways:

  • Using create() method: This method creates and saves the object in one step.
  • Using model instance and save() method: You first create an instance, then save it to the database.

Each field of the model is passed as a keyword argument with its value.

python
Model.objects.create(field1=value1, field2=value2, ...)

# OR

obj = Model(field1=value1, field2=value2, ...)
obj.save()
💻

Example

This example shows how to create a Book object with title and author fields using both methods.

python
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

# Using create() method
book1 = Book.objects.create(title='1984', author='George Orwell')

# Using instance and save()
book2 = Book(title='Brave New World', author='Aldous Huxley')
book2.save()

print(book1.title, book1.author)
print(book2.title, book2.author)
Output
1984 George Orwell Brave New World Aldous Huxley
⚠️

Common Pitfalls

Common mistakes when creating objects in Django ORM include:

  • Not calling save() after creating an instance (if not using create()), so the object is not saved to the database.
  • Missing required fields or providing invalid data types, causing errors.
  • Trying to create objects without importing the model or without proper database setup.
python
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=50)

# Wrong: forgetting to save
person = Person(name='Alice')
# person.save() is missing, so no DB record is created

# Right:
person = Person(name='Alice')
person.save()
📊

Quick Reference

Remember these tips when creating objects in Django ORM:

  • Use Model.objects.create() for quick creation and saving.
  • Use instance.save() if you need to modify the object before saving.
  • Always provide all required fields to avoid errors.
  • Check your model imports and database connection before creating objects.

Key Takeaways

Use Model.objects.create() to create and save an object in one step.
Alternatively, instantiate the model and call save() to add the object to the database.
Always provide required fields with valid values when creating objects.
Remember to call save() if you create an instance without using create().
Ensure your model is imported and database is configured before creating objects.