如何使用Django Rest Framework序列化程序一次调用相同的方法来设置多个字段?这就是我现在所做的,但这清楚地称之为方法两次。如何将其限制为仅调用一次?
class MyModel(models.Model):
def GetTwoValues(self):
foo = []
bar = []
# expensive operation
return foo, bar
class MyModelSerializer(serializers.HyperlinkedModelSerializer):
foo = serializers.SerializerMethodField()
bar = serializers.SerializerMethodField()
def get_foo(self, obj):
foo, _ = obj.GetTwoValues()
return foo
def get_bar(self, obj):
_, bar = obj.GetTwoValues()
return bar
class Meta:
model = MyModel
fields = ('FirstValue', 'SecondValue',)
答案 0 :(得分:4)
有几个选择:
1)存储值,以便只调用昂贵的方法一次。 E.g:
def _get_two_values(self, obj):
if not hasattr(self, '_two_values'):
self._two_values = obj.GetTwoValues()
return self._two_values
def get_foo(self, obj):
foo, _ = self._get_two_values(obj)
return foo
def get_bar(self, obj):
_, bar = self._get_two_values(obj)
return bar
2)从序列化程序中删除这两个字段,并在序列化程序的to_representation
方法中分配这两个值。例如:
def to_representation(self, obj):
data = super().to_representation(obj)
foo, bar = obj.GetTwoValues()
data['foo'] = foo
data['bar'] = bar
return data