Django 如何查询多个条件中的pass 2

Django 如何查询多个条件中的pass 2,django,Django,我需要通过多个条件中的两个条件的查询对象。例子: 我们有一个模型: class A(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) cost = models.IntegerField(null=True, blank=True) price = models.IntegerField(null=True, blank=True) quality = models.Int

我需要通过多个条件中的两个条件的查询对象。例子: 我们有一个模型:

class A(models.Model):
    id = models.PositiveSmallIntegerField(primary_key=True)
    cost = models.IntegerField(null=True, blank=True)
    price = models.IntegerField(null=True, blank=True)
    quality = models.IntegerField(null=True, blank=True)
    code = models.CharField(max_length=255, null=True, blank=True)
    name = models.CharField(max_length=255, null=True, blank=True)
    address = models.CharField(max_length=255, null=True, blank=True)
条件:

成本<5 价格<7 质量>0 ... 代码=1234 名称包含“苹果” 结果可能是: -成本为6、价格为6、质量为2、代码为321、名称为“asd asdsd”的“C”项 -带值的“D”:成本=4,价格=6,质量=2,代码=322,名称=xyz


如何查询作为少于2个条件传递的项?

我们可以首先用满足的条件数进行注释,然后根据该数进行筛选:

from django.db.models import Q, IntegerField
from django.db.models.functions import Cast

A.objects.annotate(
    nvalid=Cast(Q(cost__lt=5), output_field=IntegerField()) +
           Cast(Q(price__lt=7), output_field=IntegerField()) +
           Cast(Q(quality__gt=0), output_field=IntegerField()) +
           Cast(Q(code='1234'), output_field=IntegerField()) +
           Cast(Q(name__contains='apple'), output_field=IntegerField())
).filter(nvalid__gte=2)

我们可以首先用满足的条件数量进行注释,然后根据该数量进行过滤:

from django.db.models import Q, IntegerField
from django.db.models.functions import Cast

A.objects.annotate(
    nvalid=Cast(Q(cost__lt=5), output_field=IntegerField()) +
           Cast(Q(price__lt=7), output_field=IntegerField()) +
           Cast(Q(quality__gt=0), output_field=IntegerField()) +
           Cast(Q(code='1234'), output_field=IntegerField()) +
           Cast(Q(name__contains='apple'), output_field=IntegerField())
).filter(nvalid__gte=2)

A.objects.filtercost\uuu lt=5,price\uu lt=7。。。。。因此,你可以在Django中使用它,你说as less是什么意思?@WillemVanOnsem as less表示物品只需要通过n个条件中的2个,你可以使用Q to或queries@CharanjitSingh您的方式只是查询所有通过所有条件的项目。这不是我期望的a.objects.filtercost\uu lt=5,price\uu lt=7。。。。。因此,你可以在Django中使用它,你说as less是什么意思?@WillemVanOnsem as less表示物品只需要通过n个条件中的2个,你可以使用Q to或queries@CharanjitSingh您的方式只是查询所有通过所有条件的项目。这不是我的期望