Bill Noble
Bill Noble

Reputation: 6734

Add additional data to the model data returned by a Django serializer

I am using the Django REST framework to create an API. I would like to add data from more than one model to the serialised output.

At the moment my serialiser looks like this:

class ItemSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Item
        fields = ('url', 'owner', 'item_type')

I would like to add an

item_cost

value from my Costs model to the serialised output (a different cost for each item in the Item model). I would also like to add a unix timestamp value to the serialised output (one value to be placed at the end of all of the other serialised output).

My serialiser is used in a view as follows:

class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all().order_by('-date_added')
    serializer_class = ItemSerializer

I can't work out how to add the other data items to the serialised output.

Upvotes: 0

Views: 93

Answers (1)

Gustavo Carvalho
Gustavo Carvalho

Reputation: 178

You can use a SerializerMethodField from rest_framework.serializers and create a method that returns the value you are looking for, eg:

class ItemSerializer(serializers.HyperlinkedModelSerializer):
    cost = serializers.SerializerMethodField()

    def get_cost(self, obj):
        value = ... # calculate your value
        return value

    class Meta:
        model = Item
        fields = ('url', 'owner', 'item_type', 'cost')

Reference in the docs: http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

Upvotes: 2

Related Questions