44

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?

1 Answer 1

74

I think

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

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

3
  • Silly me :). Should have known.
    – duality_
    Commented Jan 14, 2014 at 6:35
  • 2
    For large numbers of MyModel wouldn't this be much slower than MyModel.objects.filter(id=100).select_related('related_model').get() since it has to do the related join on all MyModel objects instead of just the filtered list? Commented Nov 19, 2019 at 16:45
  • 5
    @AddisonKlinke: I expect them both to turn into the exact same SQL query when evaluated. Eventually the query contains "WHERE id = 100" so the database should know it doesn't have to join all rows. Commented Nov 20, 2019 at 9:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.