Django过滤器-条件查询

时间:2020-07-06 10:44:59

标签: django django-models django-rest-framework

说我有2个模型:

class Product(models.Model):                                                
  name = models.CharField(blank=True, null=True)                                             
  company = models.ForeignKey(Company, on_delete=models.CASCADE,blank=True, null=True)
  scale = models.CharField(blank=True, null=True)  

class Company(models.Model):
  name = models.CharField(blank=True, null=True)  
  scale = models.CharField(blank=True, null=True)

我对查询集使用以下过滤器

products = Products.filter.objects(scale__isnull = False, scale__in = ['L1','L2'])
products_2= Products.filter.objects(scale__isnull = True, company__scale__in = ['L1','L2'])

是否可以将这些过滤器合并为1?

1 个答案:

答案 0 :(得分:1)

是的,您可以使用Q objects [Django-doc]和按位运算符来组合条件,因此可以这样写:

from django.db.models import Q

products = Product.objects.filter(
    Q(scale__isnull=False, scale__in=['L1','L2']) |
    Q(scale=None, company__scale__in=['L1','L2'])
)

这将产生如下查询:

SELECT product.*
FROM product
LEFT OUTER JOIN company ON product.company_id = company.id
WHERE (product.scale IN (L1, L2) AND product.scale IS NOT NULL)
   OR (company.scale IN (L1, L2) AND product.scale IS NULL)