Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Allow using class properties of models for populating fields in serializers#9623

Discussion options

One of the features I miss in DRF is mapping serializer fields to properties of selected models. (It could be a good alternative to someReadWriteSerializerMethodFields )

Desired usage example:

models.py

# We have a model which stores some data in a different format than we are going to serve itclassLocation(models.Model):lattitude_degrees=models.FloatField()@propertydeflat_radians(self):returndeg_to_rad(self.lattitude_degrees)@lat_radians.setterdeflat_radians(self,lat:float):self.lattitude_degrees=rad_to_deg(lat)

serializers.py

classLocationSerializer(serializers.ModelSerializer):classMeta:model=models.Locationfields= ["lat_radians"]lat_radians=serializers.FloatField(source="lat_radians")
You must be logged in to vote

Ithink it's becauseModelSerializer cannot infer the field type without a model field.

Have you tried the following?

classLocationSerializer(serializers.ModelSerializer):lat_radians=serializers.FloatField()classMeta:model=models.Locationfields= ["lat_radians"]

Replies: 1 comment 2 replies

Comment options

Ithink it's becauseModelSerializer cannot infer the field type without a model field.

Have you tried the following?

classLocationSerializer(serializers.ModelSerializer):lat_radians=serializers.FloatField()classMeta:model=models.Locationfields= ["lat_radians"]
You must be logged in to vote
2 replies
@pktiuk
Comment options

@browniebroke

I think it's because ModelSerializer cannot infer the field type without a model field.

I updated my example to address this issue.

Have you tried the following?

I will check this out and let you know

@pktiuk
Comment options

It works as you said. Thank you for quick answer

Answer selected bypktiuk
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Labels
None yet
2 participants
@pktiuk@browniebroke

[8]ページ先頭

©2009-2025 Movatter.jp