/ / django queryset method no filtro do modelo relacionado - django, django-queryset, django-managers

django queryset method on related model filtro - django, django-queryset, django-managers

Eu tenho a seguinte configuração:

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()

Eu ativei o shell para tentar algumas consultas e criei:

  • 1 person com nenhum appointments
  • 2 person com 1 active appointment cada

e tentei isso:

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

isso funciona como eu pensei que seria:

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

Se eu tentar Person.objects.filter(appointments__active=True), Eu recebo:

FieldError: Related Field got invalid lookup: appointments

Se em vez disso, eu tento Person.objects.filter(appointments.active()=True), Eu recebo:

SyntaxError: keyword can"t be an expression

Como posso filtrar de Person.objects.filter(appointments=?) o ativo appointments cada person tem?

Respostas:

0 para resposta № 1

Acabei resolvendo criando um PersonQuerySet e um método, assim:

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

É meio chato ter que duplicar o código.