Recently, while working, I noticed a bug in my current work and learned about the difference between Django model creation and save()
method.
I initially misunderstood that when a Django model class was instantiated, the model is saved in the database. I learned it while I was implementing tests (tests are important :))
Creating Model Objects
We can create an instance of a model like how we can instantiate a Python class.
# This instantiates model 'Foo'.
foo = Foo()
# However, at this point, foo object has not been stored in the database.
# We'll need to call 'save()' method for that.
foo.save()
Customize Model Object Creation
Django document suggests that we can customize the way the model class is instantiated either by two ways:
Add a classmethod
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
@classmethod
def create(cls, title):
book = cls(title=title)
# can do something here, such as save()
return book
Add a method on a custom manager (preferred way)
class BookManager(models.Manager):
def create_book(self, title)
book = self.create(title=title)
# can do something here, such as save()
return book
class Book(models.Model):
title = models.CharField(max_length=100)
objects = BookManager()
book = Book.objects.create_book("Pride and Prejudice")