Saurabh_Jhingan
Saurabh_Jhingan

Reputation: 320

What is the difference between creating a model instance using the default Manager and Customer Manager

While going through the official Django documentation I came across the Model Instance reference section in which it is mentioned that you can create an instance of the model using the custom Model using self.create. I wanted to know what's the difference between using the create method and the custom create_method when both are using the same fields and in both the cases the data is being saved in the DB. Documentation: https://docs.djangoproject.com/en/2.2/ref/models/instances/#creating-objects

class BookManager(models.Manager):
    def create_book(self, title):
        book = self.create(title=title)
        return book

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

    objects = BookManager()

book = Book.objects.create_book("Pride and Prejudice")

Difference between these two

book2 = Book.objects.create(title="Pride and Prejudice")

Upvotes: 0

Views: 135

Answers (1)

Nafees Anwar
Nafees Anwar

Reputation: 6598

Well in this simplest case, there is no difference. The reason of describing this technique in docs is obvious there

You may be tempted to customize the model by overriding the __init__ method. If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved. Rather than overriding __init__, try using one of these approaches:

It means you may be want to set some extra/default values to model instance. If you override constructor for this purpose, it is a little unsafe (and not usually a practice in django). That's why two other techniques for doing this are described. You are mentioning one of them. You can do some extra stuff in custom manager method if you want

class BookManager(models.Manager):
    def create_book(self, title):
        # you can do some extra stuff here for instance creation
        book = self.create(title=title)
        # or here when it is saved to db
        return book

Otherwise there is no difference.

Upvotes: 1

Related Questions