Allow using class properties of models for populating fields in serializers #9623
Answered
by
browniebroke
pktiuk
asked this question in
Question & Answer
-
One of the features I miss in DRF is mapping serializer fields to properties of selected models. (It could be a good alternative to some ReadWriteSerializerMethodFields ) Desired usage example:
# We have a model which stores some data in a different format than we are going to serve it
class Location(models.Model):
lattitude_degrees = models.FloatField()
@property
def lat_radians(self):
return deg_to_rad(self.lattitude_degrees)
@lat_radians.setter
def lat_radians(self, lat: float):
self.lattitude_degrees = rad_to_deg(lat)
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = models.Location
fields = ["lat_radians"]
lat_radians = serializers.FloatField(source="lat_radians") |
Beta Was this translation helpful? Give feedback.
Answered by
browniebroke
Jan 16, 2025
Replies: 1 comment 2 replies
-
I think it's because Have you tried the following? class LocationSerializer(serializers.ModelSerializer):
lat_radians = serializers.FloatField()
class Meta:
model = models.Location
fields = ["lat_radians"] |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
pktiuk
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think it's because
ModelSerializer
cannot infer the field type without a model field.Have you tried the following?