【发布时间】:2018-09-14 08:50:01
【问题描述】:
我有以下设置:
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没有appointments - 2
person和 1activeappointment每个
并尝试过:
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 拥有的活动appointments?
【问题讨论】:
标签: django django-queryset django-managers