gpt4 book ai didi

python - Django Rest Framework Serializer Model 带参数的自定义方法

转载 作者:行者123 更新时间:2023-12-04 15:10:54 27 4
gpt4 key购买 nike

序列化器字段是否可以使用模型的自定义方法,并将参数作为其来源?就像是:

模型.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

序列化程序.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}

最佳答案

您可以尝试使用 SerializerMethodField 如果值 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

序列化器
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 并使用值 xy ),并简单地将名称用作序列化程序中的字段。例如:

楷模
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')

关于python - Django Rest Framework Serializer Model 带参数的自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40755555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com