Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django query all with filtering on the related set?

class Customer(models.Model):
  name = models.CharField(max_length=200)
  # ..


class CustomerTicket(models.Model):
  customer = models.OneToOneField(Customer)
  date = models.DateTimeField(auto_now_add=True)
  # ..

I want to query all customers. And, adding for each customer its ticket if it has one in the date range - so I will get the ticket object only if it is in the given date range, otherwise the ticket field would be null.

like image 629
user3599803 Avatar asked Nov 07 '22 08:11

user3599803


1 Answers

Try this:

from django.db import models

customers = Customer.objects.select_related('customerticket').annotate(
    ticket=models.Case(models.When(models.Q(customerticket__date__gt=date1) & models.Q(customerticket__date__lt=date2), then=models.F('customerticket')))
)

And you will get ticket as a computed field. Note that when referencing relational fields such as ForeignKey or OneToOneField, F() returns the primary key value rather than a model instance, which means your ticket field will have value of the primary key.

like image 77
Ivan Avatar answered Nov 15 '22 05:11

Ivan