[Fixed]-Django – Greedy AND Query on ManyToMany


Figured it out. There’s a great resource on SO here. In my particular case, I wanted chained filters. This is how I did it with an arbitrary number of tags.

docs = Document.objects

for tag in tags:
    docs = docs.filter(tags=tag)

This gave me the AND query I needed.


You simply want an INNER JOIN – which is the default when you filter across relations.

This should do what you want:

Document.objects.filter(tags=X, tags=Y)

This gets you each Document which has both tag X and tag Y, regardless of any other tags.


Leave a comment