除非在数据库中生成属性值,否则在不重写django的内部方法的情况下无法执行此操作
我建议不要
。
一个更优雅的解决方案可能是在
a custom queryset
根据请求生成额外字段:
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)