gpt4 book ai didi

python - 如何使用 Django 查询集预取 @property?

转载 作者:太空宇宙 更新时间:2023-11-04 02:36:04 25 4
gpt4 key购买 nike

我想将模型属性预取到 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_relatedselect_related是编译到数据库查询中的指令。将纯 Python 属性的名称传递给它是行不通的,因为您的数据库无法了解它们。您必须选择/预取该属性在后台使用的数据库字段/关系:

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.

关于python - 如何使用 Django 查询集预取 @property?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47854622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com