Django Serializer Method Field with 2 or more fields

Viewed 2270

I need to extend my serializer from existing table.

class SER_Assets(serializers.ModelSerializer):
    asset_id = serializers.SerializerMethodField()
    asset_name = serializers.SerializerMethodField()

    def get_asset_id(self, obj):
       t1 = Tbl.objects.get(tbl_id=obj.id)
       return t1.asset_id

    def get_asset_name(self, obj):
       ..

i know this method.. both function going to call same table i want to reduce function. so i need to call single function to return multiple fields.

is that possible?

2 Answers

Since you are using serializers.ModelSerializer, if the field is a model field then you can just mention the name of the model field.

Note: You can use serializers.SerializedMethodField if you need to do some manipulation on a field.

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.MyModel
        fields = ["asset_id", "asset_name", "field_3"]
        # You can also use __all__ if you want to include all the fields
        # fields = "__all__"

ModelSerializer behaves very similar to Django's ModelForm

class SER_Assets(serializers.ModelSerializer):
    asset_compound = serializers.SerializerMethodField()

    def get_asset_compound(self, obj):
        t1 = Tbl.objects.get(tbl_id=obj.id)
        return {"asset_id": t1.asset_id, "asset_name": t1.asset_name}

try this :D

Related