Home > database >  How to prefetch for individual object? (AttributeError: object has no attribute 'select_related
How to prefetch for individual object? (AttributeError: object has no attribute 'select_related

Time:03-05

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'

CodePudding user response:

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()
  • Related