我们有两个模型(简化版):
class Contestant(models.Model):
email = models.EmailField(max_length=255, unique=True)
# plus some other fields
@property
def total_points(self):
return self.points.aggregate(total=Sum('value'))['total'] or 0
class Points(models.Model):
contestant = models.ForeignKey(Contestant, related_name='points')
value = models.PositiveIntegerField()
# plus some other fields which determine based on what we
# awarded ``Points.value``
当我们显示参赛者列表及其total_points
价值时,它会为每个结果产生一个额外的查询 - 即执行以下查询:
- 获取参赛者名单
- 获取
total_points
第一个参赛者的价值 - 获取
total_points
第二位参赛者的价值 - ETC
我尝试更改查询集以预取数据,如下所示:
Contestant.objects.filter(...).prefetch_related('points')
...,但是即使它有效,在列出参赛者时也不会使用预取的数据(因此每个结果仍会尝试total_points
在单独的查询中获取)。
是否有可能:
- 以某种方式告诉 ORM 在为单个模型对象填充数据时使用 @property 字段的预取值(例如访问
Contestant.total_points
@property 方法中的预取值)? - 或以不同的方式预取它们(与上面的示例相反)?
- 还是使用完全不同的方法来达到相同的结果?
tastypie
(如果重要的话,我会在 中列出结果。)
谢谢你。