[英]Django Filter deduce ManyToMany
在Tag字段上具有多对多关系的简单模型。
class Tag(models.Model):
description = models.TextField()
class Species(models.Model):
name = models.CharField(max_length=256)
tags = models.ManyToManyField(Tag)
现在我正在尝试这样做,据我所知,它应该返回一个与标签列表中的每个tag_description匹配的列表:
tag_list = request.GET.get('q').split(',')
species = Species.objects.filter(reduce(and_, [Q(tags__description=c) for c in tag_list]))
但是它返回一个空列表。 它应该返回一些对象。
我只给一个标签就可以了
知道为什么会这样吗?
我正在使用它,如此答案所示: https : //stackoverflow.com/a/8636836/228660
正如您在该问题的注释中实际看到的那样,它实际上并不起作用;)问题是,您将对所有过滤器使用相同的联接(表示相同的对象)。 除非tag_list
中的所有项目都相同,否则将永远无法使用。 问题出在Q对象内,而不是完全过滤的查询内。
tag_list = request.GET.get('q').split(',')
# Generate a query with all species
all_species = Species.objects.all()
# Generate a list with the separately filtered species
filtered_species = [all_species.filter(tags__description=c) for c in tag_list]
# Join the filtered species together using the same method :)
species = reduce(and_, filtered_species, all_species)
我认为另一种方式是:
tag_list = request.GET.get('q').split(',')
species = Species.objects.all().distinct()
for tag in tag_list:
species = species.filter(tags__description=tag)
else:
species = Species.objects.none()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.