如何使用 Django 查询集预取 @属性?

How to prefetch a @property with a Django queryset?

我想将模型 属性 预取到 Django 中的查询集。有办法吗?

以下是三个模型:

class Place(models.Model):
    name = models.CharField(max_length=200, blank=True)
    @property
    def bestpicurl(self):
        try:
            return self.placebestpic.picture.file.url
        except:
            return None

class PlaceBestPic(models.Model):
    place = models.OneToOneField(Place)
    picture = models.ForeignKey(Picture, on_delete=models.CASCADE)

class Picture(models.Model):
    file = ImageField(max_length=500, upload_to="/images/")

我需要这样的东西:

qs = Place.objects.all().select_related('bestpicurl')

知道怎么做吗? 谢谢!

prefetch_related and select_related是编译到数据库中的指令query/ies。将纯 Python 属性 的名称传递给它是行不通的,因为您的数据库无法了解它们。您必须 select/prefetch fields/relations 属性 在幕后使用的数据库:

qs = Place.objects.select_related('placebestpic')

现在,调用 属性 不会命中数据库:

for p in qs:
    # do stuff with p.bestpicurl

即使你在这里遵循反向关系,你也没有使用 prefetch_related。来自 select_related docs:

You can also refer to the reverse direction of a OneToOneField in the list of fields passed to select_related — that is, you can traverse a OneToOneField back to the object on which the field is defined. Instead of specifying the field name, use the related_name for the field on the related object.