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

时间:2018-04-04 17:26:14

标签: django django-queryset django-managers

我有以下设置:

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来尝试一些查询并创建:

  • 1 person,没有appointment s
  • 2 person,每个active appointment

并尝试了这个:

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=?)每个appointment的有效person进行过滤?

1 个答案:

答案 0 :(得分:1)

我最终解决了它创建一个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())

有点不得不重复代码。