相关模型过滤器上的django queryset方法

django queryset method on related model filter

我有以下设置:

class Person(models.Model):
  name

class AppointmentQuerySet(models.QuerySet):
  def active(self):
    from django.utils import timezone
    return self.filter(initial_date__date__lte=timezone.now().date())

class Appointment(models.Model):
  initial_date = models.DateTimeField()
  person = models.ForeignKey(Person, related_name='appointments', blank=True, null=True)
  objects = AppointmentQuerySet.as_manager()

  def active(self):
    from django.utils import timezone
    return self.initial_date <= timezone.now().date()

我启动了 shell 来尝试一些查询并创建了:

并尝试了这个:

Person.objects.filter(appointments=True) 
# At some point yesterday, this was giving me results, 
# now it's returning an empty queryset

这和我想象的一样有效:

Person.objects.filter(appointments_isnull=False)
# returns the 2 persons with appointments but
# I have no clue from here if the appointments are active or not

如果我尝试 Person.objects.filter(appointments__active=True),我得到:

FieldError: Related Field got invalid lookup: appointments

如果相反,我尝试 Person.objects.filter(appointments.active()=True),我得到:

SyntaxError: keyword can't be an expression

我如何从 Person.objects.filter(appointments=?) 中过滤出每个 person 拥有的活动 appointment

我最终解决了这个问题,创建了一个 PersonQuerySet 和一个方法,如下所示:

class PersonQuerySet(models.QuerySet):
  def active_appointments(self):
    from django.utils import timezone
    return self.filter(appointments__initial_date__date__lte=timezone.now().date())

不过,不得不复制代码有点糟透了。