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?
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.
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).
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.
I think
MyModel.objects.select_related('related_model').get(id=100)
works, but I can't test it right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With