django query all with filtering on the related set?

怎甘沉沦 提交于 2020-06-14 07:18:23

问题


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.


回答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.




回答2:


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.




回答3:


Use queryset.filter:

from django.utils import timezone

Customer.objects.exclude(customerticket=None).filter(customerticket__date=timezone.now())


来源:https://stackoverflow.com/questions/49792062/django-query-all-with-filtering-on-the-related-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!