简体   繁体   English

Django筛选器推论出ManyToMany

[英]Django Filter deduce ManyToMany

Simple models with many to many relations on the Tag field. 在Tag字段上具有多对多关系的简单模型。

class Tag(models.Model):
    description = models.TextField()

class Species(models.Model):
    name = models.CharField(max_length=256)
    tags = models.ManyToManyField(Tag)

Now Im trying this, and as I understand, it should return a list that matches every tag_description in the tags list: 现在我正在尝试这样做,据我所知,它应该返回一个与标签列表中的每个tag_description匹配的列表:

tag_list = request.GET.get('q').split(',')
species = Species.objects.filter(reduce(and_, [Q(tags__description=c) for c in tag_list]))

But its returning an empty list. 但是它返回一个空列表。 It should be returning some objects. 它应该返回一些对象。

It works when I give it only one tag 我只给一个标签就可以了

any idea why this is happening? 知道为什么会这样吗?

Im using it as was shown in this answer: https://stackoverflow.com/a/8636836/228660 我正在使用它,如此答案所示: https : //stackoverflow.com/a/8636836/228660

As you can actually see in the comments of that question, it doesn't actually work ;) The problem is that you will be using the same join (which means the same object) for all filters. 正如您在该问题的注释中实际看到的那样,它实际上并不起作用;)问题是,您将对所有过滤器使用相同的联接(表示相同的对象)。 Unless all items in tag_list are identical this will never work. 除非tag_list中的所有项目都相同,否则将永远无法使用。 The problem lies within the Q objects instead of full filtered queries. 问题出在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)

I think another way of doing this would be: 我认为另一种方式是:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM