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')

如何预取单个对象?

即select_related 一个对象的外键:

# 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'

select_related 用于查询集,在 first() 的结果上使用它会使您处理单个实例,从而导致错误。

所以在调用 first() 之前你必须先做 select_related:

Foo.objects.select_related("bar").first()