Is it possible for a serializer field to use a model's custom method with parameters as its source? Something like:
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')
It should return as a response something similar to:
{'x': 1, 'y': 0}
You can try using the SerializerMethodField as follows if the values x and y are static:
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')
Another possible way of doing this is to create two separate properties (that explicitly call the sample_method with the value x or y) on your model itself and simply use the names as fields in your serializer. For example:
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With