如何使用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',)
解决方法:
有几种选择:
1)存储值,以便仅调用一次昂贵的方法.例如.:
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