Home > Net >  modify django model field on serializer
modify django model field on serializer

Time:07-19

i have a model definition

Class Book():
          name = textfield()
          edition = textfield() 

i want the the name of the book as "edition name" if there is a edition data on the book object. otherwise i want to return only the book. how can i acheive that? can i use a serializermethod on the book serializer as

class BookSerializer(

):
    name = serializers.SerializerMethodField()
    def get_name(self,book):
        if book.edition:
            return f"{book.edition}{book.name}"
        return book.name 

this way the name is being saved with the edition number. i dont want to save the edition number with the name. i just want the serializer should return name field as "edition name" if there is a edition else only the name but not save it on the model.

CodePudding user response:

This might not be the best way, but its how I have been doing it.
By overriding to_representation function, you can change the serialized result only.

like so


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('name', 'edition')
    
    def to_representation(self, instance:Book):
        out = super().to_representation(instance)
        # change the name to <name edition>
        out['name'] = f"{instance.edition if instance.edition else ""} {instance.name}"
        # remove the original 'edition' so it doesnt show in output
        out.pop('edition')

so this way when you serialize the bool obj, you only get a 'name' field that contains "{edition} {name}", but you can still use this serializer to deserialize and construct a Book obj later.

  • Related