[Answer]-Django: how to build relations and queries the best way?

1👍

Since all the information you need to send to the template is in the Translation model, I would do the query on that model, and send that to the template. The only thing you need that is in the Article model is the visible field, so you can filter on that:

article = ContentType.objects.get_for_model(Article)
article_ids = Article.objects.filter(visible=True).values_list('id')
translations = Translation.objects.filter(content_type=article, object_id__in=article_ids)
context = {'recent_news_list: translations}

This is just three queries: one to get the ContentType (although this will probably be cached automatically), one to get the translations, and one to get the articles (and Django may indeed do the third as a subquery of the second).

It’s always going to be slightly complicated though; that’s the price you pay for using generic relations. I know your other question does have multiple types related to Translation, but if you can get away without doing that things would indeed be much simpler.

Leave a comment