I have two models Article and Blog related using a foreign key. I want to select only blog name while extracting the article.
articles = Articles.objects.all().select_related('blog__name')
The query generated shows that it selected all the fields from the Blog model. I tried using only() and defer() with select_related but both didn't work out.
articles = Articles.objects.all().select_related('blog__name').only('blog__name', 'title', 'create_time')
The above query resulted in error: Invalid field name(s) given in select_related: Choices are: blog
How do i generate a query so that only article fields and blog name is selected?
only
don't show any examples of traversing relations, while the docs forselect_related
only show examples of traversing multiple relations (i.e.rel__rel
, notrel__field
). seems like the best you can do isarticles = Articles.objects.all().select_related('blog').only('blog', 'title', 'create_time')
– Earpprefetch_related
, but this way you will end up with 2 queries instead of one.Articles.objects.all().prefetch_related(Prefetch('blog', queryset=Blog.objects.all().only('name')))
– Simferopol