Selecting specific fields using select_related in Django Selecting specific fields using select_related in Django django django

Selecting specific fields using select_related in Django


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')


You can use annotate() for this.

>>> a = Articles.objects.annotate(blog_name=F('blog__name')).first()>>> a.title>>> a.blog_name


It can be done by adding one more field into only section, it's blog (I assume it helps Django to keep relation between objects (Article & Blog):

articles = Articles.objects.select_related(    'blog',).only(    'blog',    'blog__name',    'title',    'create_time',)

Tested on Django==2.2.19