Hanpan
Hanpan

Reputation: 10251

Django ManyToMany join query

I'm sure this is really simple, but I can't for the life of me find any documentation explaining how to do this.

How do I get the results of a ManyToMany field inside a join as opposed to doing this:

{% for tag in article.tags.all %}

Which results in an extra query? What I'd like to do is fetch all related tags when I retrieve the initial article, so I could then do something like:

{% for tag in article.tags %}

Without the .all and the extra query.

Thanks!

Upvotes: 1

Views: 933

Answers (2)

Dmitry Shevchenko
Dmitry Shevchenko

Reputation: 32404

django-batch-select does just what you want and a bit more :)

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599520

You can't do this. select_related() is the usual way to follow joins in a single query, but it doesn't work with ManyToMany relations.

Upvotes: 1

Related Questions