Selecting specific fields using select_related in Django
21,531
Solution 1
You can use annotate() for this.
>>> a = Articles.objects.annotate(blog_name=F('blog__name')).first()
>>> a.title
>>> a.blog_name
Solution 2
select_related
should be use on the whole model, and then you can filter it more. This will work:
Articles.objects.select_related('blog').only('blog__name', 'title', 'create_time')
Author by
anonDuck
Updated on May 22, 2021Comments
-
anonDuck about 3 years
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?
-
anonDuck over 8 yearsUsing .values returns dictionary instead of queryset object, which makes it useless to use the relations like 'file.url' or 'file.name' in the templates or view. Is there any other way possible?
-
T. Opletal over 8 years@RA123 I edited my answer. Tried it and this way it works for me
-
anonDuck over 8 yearsThis is also not working. I'm on Django 1.8. It gives the following error - "Invalid field name(s) given in select_related: 'blog'. Choices are: blog" When i remove '__name' from 'blog__name' in 'only', it works fine but fetches all the fields.
-
lechup over 7 yearsIt's working on 1.10, I'm using it with
QuerySet.defer()
, thanks! -
Shashank Hegde over 4 yearsThis is not the expected answer. The below one solves the purpose.
-
Mohammed Shareef C over 4 yearsSometimes, this serves the purpose. anyway both are significant
-
Clint Eastwood almost 3 yearsoriginal question was: "How do i generate a query so that only article fields and blog name is selected?" This is fetching all fields from Blog, right? If so, it wouldn't answer the question properly. Correct?