Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prefetch for individual object? (AttributeError: object has no attribute 'select_related')

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'
like image 833
Chris Avatar asked Nov 17 '25 09:11

Chris


1 Answers

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()
like image 158
Brian Destura Avatar answered Nov 19 '25 09:11

Brian Destura



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!