Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework serializing with dynamic fields

I am having an issue with serialization. I have a queryset of objects e.g.:

uvs = UserVehicles.objects.all()

Some of those objects are expired, some are not. I would like to have different fields in serializer, depending on expiry information. For example, I would like to exclude status and distance_travelled fields from expired objects. What is the easiest way to achieve that? I tried with the next code, but self.object in init method contains an array, so it would remove fields for all objects, not just expired ones.

serialized_data = UserVehicleSerializer(uvs, many=True).data

class UserVehicleSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserVehicle
        fields = ('type', 'model', 'status', 'distance_travelled',)

    def __init__(self, *args, **kwargs):
        super(UserVehicleSerializer, self).__init__(*args, **kwargs)

        if self.object.is_expired:
            restricted = set(('distance_travelled', 'status',))
            for field_name in restricted:
                self.fields.pop(field_name)
like image 592
miloslu Avatar asked Nov 02 '15 11:11

miloslu


2 Answers

I would suggest keeping the business logic out of the serializer. you could create a separate serializer for expired vehicles/objects and a separate serializer for active vehicles and choose the correct serializer in the view. That way, if your business logic goes in different directions for each type of vehicle , it should be easy to manage.

like image 195
bir singh Avatar answered Sep 26 '22 15:09

bir singh


You could do that in the Serializer's to_representation().

http://www.django-rest-framework.org/api-guide/fields/#custom-fields has examples for Fields but Serializers do inherit from Field. Just call the parent's to_representation and remove the fields you don't want.

like image 41
Linovia Avatar answered Sep 26 '22 15:09

Linovia