Feature request: option in Meta
to rename fields in ModelSerializer
#8994
Replies: 2 comments 3 replies
-
can you share some code sample/example of what you are suggesting? |
Beta Was this translation helpful? Give feedback.
-
A feature like this would be useful, so I could rename the output field. Currently you need to add a new field by that name on the serializer, and specify all fields explicitly. I find myself wanting all the auto-generated field properties (max length, help text, etc) but only rename the field. I suppose an alternative would be to make creating a serializer field from a model field easier. Perhaps something like this: class User(Model):
name = CharField()
email_address = CharField(max_length=1000)
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = ["name", "email"] # or "__all__"
renamed_fields = {
"email": "email_address"
} If I could easily create a serializer field from a model field that would work as well. I always specify all my fields directly anyway class UserSerializer(ModelSerializer):
email = ModelSerializer.build_field(User.email_address)
class Meta:
model = User
fields = ["name", "email"] |
Beta Was this translation helpful? Give feedback.
-
As far as I know, there are 3 ways to serialize a Django model field under a different name:
serializers.ModelField
serializers.SerializerMethodField
source
parameter offields.Field
.All of them are quite tedious. The first one necessitate to intantiate a least one instance of the model, which is a waste of resources and rather counter intuitive, the second necessitates to create accessors for every field and the third defeats the auto-mapping feature of
ModelSerializer
.It would be nice if renaming a field was simpler. It could take the form of a
renamed_fields
attribute inModelSerializer.Meta
. Alternatively,ModelField
can be modified to accept amodel_field_name
argument and fetch the model field based on this (although I have a preference for the first method).I am ready to implement that feature with a little guidance.
Beta Was this translation helpful? Give feedback.
All reactions