可以使用自定義的經理讓事情變得乾燥,增強可讀性(明確指定的過濾器總是比拖着一個複雜的過濾器更好)
class GraduateManager(models.Manager):
def get_queryset(self):
return super(GraduateManager, self).get_queryset().filter(graduated=True)
class UndergraduateManager(models.Manager):
def get_queryset(self):
return super(Undergraduate, self).get_queryset().filter(graduated=False)
class Student(models.Model):
graduated = BooleanField()
graduates = GraduateManager()
undergraduates = UndergraduateManager()
要使用它,你就會得到一個正常的查詢集,你可以操縱根據需要
Student.graduates.all(), or .filter(), or .count() etc
參考https://docs.djangoproject.com/en/1.8/topics/db/managers/#modifying-initial-manager-querysets
你的答案解決了我的問題。謝謝。 – JordanChina