0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

That is perfect Gustavo! Is there a way to access the query params from the calling url in the get_cost function so I can do an action that depends on the query?
Yes you can. From inside the method, you can access the QueryDict: self.context.get('request').query_params

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.