这是Model,要实现的过滤器属性为Brand,Product_type,Price(price_range)。如果品牌可能不止一个,并且价格在价格范围内(例如2000-3000),我尝试使用链式过滤器
objects = Tyre.objects.filter(brand__name__in=brands).filter(product_type__in=types).filter(
tyre_price__price__range=(min_price, max_price))
但是,如果任何一个属性发送为空,则结果为空queryset。如何实施? 预先感谢。
class Brand(models.Model):
name = models.CharField(max_length=100)
brand_type = models.CharField(max_length=30)
class Tyre(models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.DO_NOTHING)
product_type = models.CharField(max_length=100)
normalsectionwidth = models.CharField(max_length=100)
normalaspectratio = models.CharField(max_length=100)
constructiontype = models.CharField(max_length=100)
rimdiamter = models.CharField(max_length=100)
loadindex = models.CharField(max_length=100)
speedsymbol = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
pattern = models.CharField(max_length=100)
description = models.CharField(max_length=100)
warranty_summery = models.CharField(max_length=500)
left_image = models.CharField(max_length=500)
name = models.CharField(max_length=100)
right_image = models.CharField(max_length=500)
front_image = models.CharField(max_length=500)
back_image = models.CharField(max_length=500)
mrp = models.CharField(max_length=100)
construction_type_R = models.CharField(max_length=100)
brand = models.ForeignKey(Brand,models.DO_NOTHING, related_name='brand')
brand_model = models.ForeignKey(BrandModel, models.DO_NOTHING)
warranty_by_year = models.CharField(max_length=100)
warranty_by_km = models.CharField(max_length=100)
class TyrePrices(models.Model):
tyre = models.ForeignKey(Tyre, related_name='tyre_price')
price = models.IntegerField()
vendor = models.ForeignKey(User)
discount = models.IntegerField()
description = models.TextField(max_length=500)
discount_price = models.IntegerField()
stock = models.BooleanField(default=True, db_column='stock')
答案 0 :(得分:0)
您当前的ORM查询正在数据库级别使用AND子句,因此您没有按照异常获得结果
尝试一下
from django.db.models import Q
objects = Tyre.objects.filter(Q(brand__name__in=brands) | Q(product_type__in=types) | Q(tyre_price__price__range=(min_price, max_price)))