Home > Software design >  Does create() method save model object to Django database?
Does create() method save model object to Django database?

Time:07-31

I just came across using create methods in Djangos models.Model subclass. Documentation has this example code:

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")

Does this already save new Book object to database? My intuition suggests that save() method should be called on the line # do something with the book or else it should not work. However when I try testing it, it seems that addin save() to it does not affect anything what so ever. Why is that the case and how does it actually save object to database?

PS. I came across this while trying to learn testing with TestCase. If classmethod does not save anything to database problem is probably my testing code, but that would be whole another question.

CodePudding user response:

Does this already save new Book object to database?

No, it just creates a Book object with the given title, but it is not saved to the database, you thus should save it:

book = Book.create('Pride and Prejudice')
book.save()

it might be better to work with .objects.create(…) [Django-doc], this will call save with force_insert=True, which will slightly optimize the insertion to the database:

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

    @classmethod
    def create(cls, title):
        # will store this in the database
        book = cls.objects.create(title=title)
        # do something with the book
        return book

or with:

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

    @classmethod
    def create(cls, title):
        book = cls(title=title)
        # will store this in the database
        book.save(force_insert=True)
        # do something with the book
        return book
  • Related