Reputation: 668
How do I prefetch for a single object?
I.e. select_related for a ForeignKey for one object:
# models.py
class Bar(models.Model):
title = models.CharField()
class Foo(models.Model):
bar = models.ForeignKey(Bar)
b1 = Bar.objects.create(title="Bar")
f1 = Foo.objects.create(bar=b1)
Foo.objects.all().first().select_related("bar")
# AttributeError: 'Foo' object has no attribute 'select_related'
Upvotes: 3
Views: 1889
Reputation: 12068
select_related
is used on querysets, and using it on the result of first()
will have you working on a single instance, causing the error.
So you'll have to do select_related
first before calling first()
:
Foo.objects.select_related("bar").first()
Upvotes: 4