Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting specific fields using select_related in Django

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?

like image 668
RA123 Avatar asked Feb 20 '16 13:02

RA123


People also ask

What does Select_related do in Django?

In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects. In this article, we will see how it reduces the number of queries and make the program much faster.

What's the difference between Select_related and Prefetch_related in Django ORM?

The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object ( ModelA in the above example).

What is select related and Prefetch_related?

select_related and prefetch_related are ways to optimize database querying patterns when accessing related items. Both works on the same principle of prefetching data from the database, however, they take different approaches to do so. We will be using a decorator to print all the stats for the query.


2 Answers

You can use annotate() for this.

>>> a = Articles.objects.annotate(blog_name=F('blog__name')).first() >>> a.title >>> a.blog_name 
like image 36
brki Avatar answered Sep 30 '22 05:09

brki


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') 
like image 172
T. Opletal Avatar answered Sep 30 '22 05:09

T. Opletal