阅读Django文档后,建议Foo
通过create_foo
在管理器中定义模型来为命名模型创建自定义创建方法:
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")
我的问题是,为什么前一个方法更喜欢简单地重写基类的create
方法:
class BookManager(models.Manager):
def create(self, title):
book = self.model(title=title)
# do something with the book
book.save()
return book
class Book(models.Model):
title = models.CharField(max_length=100)
objects = BookManager()
book = Book.objects.create("Pride and Prejudice")
Imo似乎只有重写create
才能防止任何人意外地使用它来制作格式不正确的模型实例,因为create_foo
始终可以完全绕开它:
class BookManager(models.Manager):
def create_book(self, title):
book = self.create(title=title, should_not_be_set_manually="critical text")
return book
class Book(models.Model):
title = models.CharField(max_length=100)
should_not_be_set_manually = models.CharField(max_length=100)
objects = BookManager()
# Can make an illformed Book!!
book = Book.objects.create(title="Some title", should_not_be_set_manually="bad value")
这样做是否有任何好处,如文档所建议的那样,或者实际上create
是客观上更好地覆盖了它?