The Django documentation contains the following note:

You may be tempted to customize the init method. It can be a question. Rather than overriding init , try using one of these approaches:

Add a classmethod on the model class:

from django.db import models class Book(models.Model): title = models.CharField(max_length=100) @classmethod def create(cls, title): book = cls(title=title) # do something with the book return book book = Book.create("Pride and Prejudice") 

Add a method to a custom manager (usually preferred):

 class BookManager(models.Manager): def create_book(self, title): book = self.create(title=title) # do something with the book return book class Book(models.Model): title = models.CharField(max_length=100) objects = BookManager() book = Book.objects.create_book("Pride and Prejudice") 

Perhaps a similar question has already been asked, but still, what is the difference between creating an instance of a model through @classmethod and through Manager ? I want to understand more deeply the difference between these two approaches, and why it is precisely the second one I am preferred.

    1 answer 1

    From the position of python - nothing. You have a class, you create an instance and call its method.

    From the perspective of django - also in nothing. You create an instance of the model and save it.

    The documentation only shows that you can dodge it this way - through a method, or through a manager. But the priority is to use the manager, because the model itself should not control either the selection of elements or the creation. It can only somehow save (say, add time to create when you call save) or start validating itself (such as the model's validate method, which, for example, is called when validating with a form of data consistency, say unique or unique_together - the uniqueness of records in bd).

    But she does not create herself. This is done by the model manager. His most used function is, of course, the selection of elements, but in general he is responsible for the correct transfer of parameters into the model itself, sampling of additional fields on request, and much more for that. This is just the logic of django, so modularity is ensured.

    You can take a look at the source of creating users in django for interest - there is just a bunch of all the parameters passed to the model. Imagine you would have spiked it all into a model. And the fact that you brought in the documentation is the simplest case. Well, in the case of redefining the model, you can drag and drop methods for creating and selecting instances, for example.