1๐
โ
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
Source:stackexchange.com