Django Filter演绎了ManyToMany

时间:2014-09-13 09:26:52

标签: python django django-queryset

标记字段中具有多对多关系的简单模型。

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

2 个答案:

答案 0 :(得分:1)

正如您在该问题的评论中实际看到的那样,它实际上并不起作用;) 问题是您将为所有过滤器使用相同的连接(这意味着相同的对象)。除非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)

答案 1 :(得分:1)

我认为另一种方法是:

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()