Feature request: option in Meta
to rename fields in ModelSerializer
#8994
-
As far as I know, there are 3 ways to serialize a Django model field under a different name:
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 It would be nice if renaming a field was simpler. It could take the form of a I am ready to implement that feature with a little guidance. |
Beta Was this translation helpful? Give feedback.
Replies: 3 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.
-
I've smacked into this one today and the fix is actually pretty straightforward and django-esque. Set a Given the posted example: from django.db import models
class Connection(models.Model):
date = models.DateTimeField(auto_now_add=True)
user = organisation = models.ForeignKey(models.CASCADE) Then a corresponding serializer that does what the OP wants would be: from rest_framework import serializers
class OrganisationSerializer(serializers.HyperlinkedModelSerializer):
creation_date = serializers.DateTimeField(source="date")
class Meta:
model = Connection
fields = ["creation_date", "user"] |
Beta Was this translation helpful? Give feedback.
I've smacked into this one today and the fix is actually pretty straightforward and django-esque.
Set a
source
attribute and stick to the regular field serializers wherever you can. Using ModelField should probably be an exception not the rule.Given the posted example:
Then a corresponding serializer that does what the OP wants would be: