[Answered ]-Django Filter deduce ManyToMany

1πŸ‘

βœ…

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. The problem lies within the Q objects instead of full filtered queries.

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)
πŸ‘€Wolph

1πŸ‘

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()
πŸ‘€schillingt

Leave a comment