Question:
I just came across usingcreate
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.Answer:
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
If you have better answer, please add a comment about this, thank you!
If you like this answer, you can give me a coffee by <a href=”https://violencegloss.com/mkw7pgdwwr?key=2a96ade6f3760c7e63343a320febb78e”>click here</a>
Source: Stackoverflow.com
Leave a Review