由于您将颜色存储为纯文本而不使用相关模型,因此您无法使用所需的过滤器类型。
正确的做法是使用ManyToManyField:一种颜色可以有多种产品,一种产品可以有多种颜色:
class Color(models.Model):
name = models.CharField(max_length=255)
class Product(models.Model):
colors = models.ManyToManyField(Color, related_name='colors')
然后,您可以像这样添加颜色:
blue = Color(name='blue')
blue.save()
red = Color(name='red')
red.save()
my_product = Product()
my_product.save()
my_product.colors.add(blue)
如果您想查询所有红色或蓝色的产品,只需:
Product.objects.filter(colors__in=[red, blue]) # Red and blue being Color instances
如果您想要所有红色和蓝色的产品,只需按照here 所述进行操作:
Product.objects.filter(colors=red).filter(colors=blue) # Red and blue being Color instances
像这样的链接过滤器不是特别方便,所以您可能需要一个自定义的QuerySet 来为您做这件事:
class AllManyToManyQuerySet(models.QuerySet):
def filter_all_many_to_many(self, attribute, *args):
qs = self
for arg in args:
qs = qs.filter(**{attribute: arg})
return qs
class Product(models.Model):
colors = models.ManyToManyField(Color, related_name='colors')
objects = AllManyToManyQuerySet.as_manager()
并像这样使用它:
Product.objects.all().filter_all_many_to_many('colors', red, blue) # red and blue being color instances
另一种过滤方法是:
product_list = Product.objects.filter(reduce(operator.and_, [Q(colors__name=c) for c in colors]))
它未经测试,但它应该可以工作,如果你在其他地方需要它,你可以在其他类上使用查询集,让你的代码保持干净和干燥;)