简体   繁体   English

django查询所有与相关集上的过滤?

[英]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. 并且,如果每个客户在日期范围内有一个票证,则为其添加票证 - 因此,只有当票证对象在给定的日期范围内时才会获得票证对象,否则票证字段将为空。

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. 并且您将获得作为计算字段的ticket 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. 请注意,在引用诸如ForeignKey或OneToOneField之类的关系字段时,F()将返回主键值而不是模型实例,这意味着您的ticket字段将具有主键的值。

To get customers with related tickets with one query you can use select_related . 要通过一个查询为客户提供相关票证,您可以使用select_related To make complex condition you can use Q 要制作复杂的条件,您可以使用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. 这将按客户日期过滤数据。

Use queryset.filter: 使用queryset.filter:

from django.utils import timezone

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM