Zigmas
Zigmas

Reputation: 335

Adding additional data to django rest framework viewset response

Curently I have a viewset of an example Warehouse and I want to pass additional 'filter' list to each dictionary that is returned.

My WarehouseViewSet:

class WarehouseViewSet(viewsets.ReadOnlyModelViewSet):
    filters = [{'date': 'Date/Time'}]

    queryset = Warehouse.objects.all()
    serializer_class = WarehouseSerializer

WarehouseSerializer:

class WarehouseSerializer(serializers.ModelSerializer):

    class Meta:
        model = Warehouse
        field = ('name', 'address', 'action_list')

Currently I get an json list response like:

[
    {
        "id": 1, 
        "name": "Brameda Warehouse", 
        "address": "Bergijk"
    }, 
    {
        "id": 2, 
        "name": "Amazon", 
        "address": "UK"
    }
]

I would like to get:

[
    {
        "id": 1, 
        "name": "Brameda Warehouse", 
        "address": "Bergijk"
        "filters": [
                    {'date': 'dateTime'}, {'actove': 'ActiveObject'}
                   ]
    }, 
    {
        "id": 2, 
        "name": "Amazon", 
        "address": "UK",
        "filters": [
                    {'date': 'dateTime'}, {'actove': 'ActiveObject'}
                   ]
    }
]

I understand that having one filter is enough outside the objects dictionary, but I would like to know how to pass lists inside objects.

Any ideas how I can pass additional lists that would be returned as json object would be appreaciated.

Upvotes: 1

Views: 1854

Answers (1)

spectras
spectras

Reputation: 13542

I feel a bit unclear as to what you want, but if you just want to add some read-only computed field to the output, you can use SerializerMethodField:

class WarehouseSerializer(serializers.ModelSerializer):
    # your other declared fields here
    filters = serializers.SerializerMethodField()

    # your Meta options here

    def get_filters(self, obj):
        return ['some', 'stuff', 'here', {'and': 'more'}]
  • The method has to be named get_field_name (there is an option to change it but I don't really see any point using it).
  • You get the instance being serialized as obj.
  • You may return anything that is made of regular types (numbers, strings, dicts, lists, tuples, booleans, None).
  • If the data has to come from outside, you should have the caller add it to the context, and it will be available on self.context['foobar'].

Upvotes: 3

Related Questions