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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With