【问题标题】:django queryset method on related model filter相关模型过滤器上的django queryset方法
【发布时间】: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 和 1 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=?) 中过滤每个person 拥有的活动appointments?

【问题讨论】:

    标签: django django-queryset django-managers


    【解决方案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())
    

    不得不重复代码有点糟糕。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      相关资源
      最近更新 更多