Skip to main content
 首页 » 编程设计

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

2024年09月07日49mayingbao

我想将模型属性预取到 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和 select_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.