Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select_related when using .get() in django?

Tags:

django

If I use the get() function to get one item from the model, I cannot use select_related(), as that object doesn't have it, but I'd still like to use it to save myself one DB query. What I'm saying is that this doesn't work (and I'd like it to):

MyModel.objects.get(id=100).select_related('related_model') 

What I can do is not what was intended. I can do this:

MyModel.objects.filter(id=100).select_related('related_model')[0] 

But it's not the same. Can I do something about it?

like image 892
duality_ Avatar asked Jan 13 '14 20:01

duality_


People also ask

What is the use of Select_related () in Django ORM query?

Using select_related() Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects.

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

For which of the following Select_related is applicable?

We use select_related when the object that you're going to select is a single object, which means forward ForeignKey, OneToOne and backward OneToOne . select_related works by creating an SQL join and including the fields of the related object in the SELECT statement.


1 Answers

I think

MyModel.objects.select_related('related_model').get(id=100) 

works, but I can't test it right now.

like image 132
RemcoGerlich Avatar answered Sep 18 '22 17:09

RemcoGerlich