5
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.

2
  • you want customers with tickets ? Commented Apr 12, 2018 at 8:57
  • No, I want all of them, adding the ticket as a computed field, which might be null Commented Apr 12, 2018 at 9:00

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I don't know why but the output is very large with many duplicated rows
What do you mean by duplicated rows?
I get the same Customer multiple times
Do you get duplicates if you run Customer.objects.all()?
I don't. Isn't annotate meant to be used for group by statement?
0

To get customers with related tickets with one query you can use select_related. To make complex condition you can use Q

from django.db.models import Q Customer.objects.select_related('customerticket').filter(Q(customerticket__date__range=["2018-04-11", "2018-04-12"]) | Q(customerticket__isnull=True)) 

This will filter data by customerticket date.

4 Comments

Forgot to mention, I also need to filter by the date field. Edited the question
Tried this way, it does not query all the customers, this query forces customer to have a ticket. I want to query all the customers, so the filter condition should be only on the related field
@user3599803 just add or condition, see my updates.
It sill gives me only in the date range and not all the Customers, so isnull condition does not seem to work
0

Use queryset.filter:

from django.utils import timezone Customer.objects.exclude(customerticket=None).filter(customerticket__date=timezone.now()) 

2 Comments

Same problem as with the above answer
Edited my answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.