[Answer]-Optimized query to match and exclude multiple ManyToMany entries

1👍

If you have already identified that line as culprit with the help e.g. of django-debug-toolbar I’d try two things:

  • Filter using in instead of different clauses

    Models.objects.filter(tags__in=[tag_1, tag_2])

  • Filter using ids instead of object

    Model.objects.filter(tags__id=tag_1.id).filter(tags__id=tag_2.id)

You can even combine the two.

Leave a comment