我有一个模型,其中包含我想要包含的@property
vals = MyModel.objects.values()
Another S/O post建议执行此操作的方法是覆盖经理类的get_queryset
方法,并通过调用annotate(xtra_field=...)
进行扩充。
问题是我找不到如何使用模型属性执行此操作的示例。我尝试过类似的东西
super(SuperClass, self).get_queryset().annotate(xtra_fld=self.model.xtra_prop)
以及其中的许多变体,都不起作用。
问题,我认为注释论证的RHS应该是什么?
(而且,是的,我知道还有其他更笨重的方法可以做到这一点,例如迭代values()
返回的内容并添加属性。只是不是一个非常优雅(甚至是django)的解决方案,对我来说。
答案 0 :(得分:3)
除非您在数据库中生成属性值,否则如果不覆盖django的内部方法 - 我推荐,则无法执行此操作。
更优雅的解决方案可能是向send curl output through pipe添加额外的方法,根据请求生成额外的字段:
from django.db import models
class AreaQuerySet(models.QuerySet):
def values_with_area(self, *fields):
# width & height are always required to calculate the area
fields = set(fields)
fields.update(['width', 'height'])
for row in self.values(*fields):
row['area'] = Widget.calculate_area(row['width'], row['height'])
yield row
class Widget(models.Model):
# ...
objects = AreaQuerySet.as_manager()
@classmethod
def calculate_area(cls, width, height):
return width * height
@property
def area(self):
return Widget.calculate_area(self.width, self.height)