Đọc tài liệu Django , nó khuyên bạn nên tạo một phương thức tạo tùy chỉnh cho một mô hình được đặt tên Foobằng cách định nghĩa nó như create_footrong trình quản lý:
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")
Câu hỏi của tôi là tại sao cái trước được ưa thích chỉ đơn giản là ghi đè createphương thức của lớp cơ sở :
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 có vẻ như chỉ ghi đè createsẽ ngăn bất kỳ ai vô tình sử dụng nó để tạo một ví dụ mô hình không phù hợp, vì create_fooluôn có thể được bỏ qua hoàn toàn:
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")
Có bất kỳ lợi thế nào khi làm điều đó như các tài liệu đề xuất, hoặc thực sự ghi đè createchỉ là khách quan tốt hơn?