27
You can use annotate() for this.
>>> a = Articles.objects.annotate(blog_name=F('blog__name')).first()
>>> a.title
>>> a.blog_name
79
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')
- [Django]-Pagination in Django-Rest-Framework using API-View
- [Django]-Need to convert a string to int in a django template
- [Django]-Django Forms: pass parameter to form
1
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
- [Django]-What does on_delete do on Django models?
- [Django]-How can one change the type of a Django model field from CharField to ForeignKey?
- [Django]-How to convert JSON data into a Python object?
Source:stackexchange.com