12
我對使用Django自定義模型管理器的正確方式感到困惑 - 基於文檔,您可以爲一個模型創建一系列管理器作爲過濾的一種方式。但爲什麼不創建一個具有一系列過濾功能的經理類?一種方法比另一種更好嗎?爲什麼?Django自定義模型管理器
例如:
class MaleManager(models.Manager):
def get_query_set(self):
return super(MaleManager, self).get_query_set().filter(sex='M')
class FemaleManager(models.Manager):
def get_query_set(self):
return super(FemaleManager, self).get_query_set().filter(sex='F')
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
sex = models.CharField(max_length=1, choices=(('M', 'Male'), ('F', 'Female')))
people = models.Manager()
men = MaleManager()
women = FemaleManager()
與
class PersonManager(models.Manager):
def males(self):
return super(MaleManager, self).get_query_set().filter(sex='M')
def females(self):
return super(FemaleManager, self).get_query_set().filter(sex='F')
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
sex = models.CharField(max_length=1, choices=(('M', 'Male'), ('F', 'Female')))
people = PersonManager()
Person.people.females() # to get list of females
Person.people.males() # to get a list of males
是的,但兩種方法正在返回querysets ...所以不會Person.objects.females.filter(first_name ='簡')仍然工作? ... –
@ 9位:不要忘了實際調用該方法。 –
@ IgnacioVazquez-Abrams你是什麼意思? Person.people.females.filter(first_name ='Jane')不會調用方法然後過濾嗎? –