序列化器字段是否可以使用模型的自定义方法以及参数作为其来源?类似的东西:
models.py
class Sample(models.Model):
name = models.CharField(max_length=100, default=None)
def sample_method(self, param):
if param == 'x':
return 1
elif param == 'y':
return 0
serializers.py
class SampleSerializer(serializers.ModelSerializer):
x = # serializer field that returns sample_method custom method with a parameter of 'x'
y = # serializer field that returns sample_method custom method with a parameter of 'y'
class Meta:
model = Sample
fields = ('x', 'y')
它应该作为响应返回类似于:
{'x': 1, 'y': 0}
答案 0 :(得分:2)
如果值x
和y
是静态的,您可以尝试使用SerializerMethodField
,如下所示:
class Sample(models.Model):
name = models.CharField(max_length=100, default=None)
def sample_method(self, param):
if param == 'x':
return 1
elif param == 'y':
return 0
class SampleSerializer(serializers.ModelSerializer):
x = SerializerMethodField()
y = SerializerMethodField()
class Meta:
model = Sample
fields = ('x', 'y')
def get_x(self, obj):
return obj.sample_method('x')
def get_y(self, obj):
return obj.sample_method('y')
另一种可能的方法是创建两个单独的属性(在模型本身上显式调用sample_method
值x
或y
)并简单地使用名称作为序列化程序中的字段。例如:
class Sample(models.Model):
name = models.CharField(max_length=100, default=None)
def sample_method(self, param):
if param == 'x':
return 1
elif param == 'y':
return 0
@property
def x(self):
return self.sample_method('x')
@property
def y(self):
return self.sample_method('y')
class SampleSerializer(serializers.ModelSerializer):
class Meta:
model = Sample
fields = ('x', 'y')