7

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)

2 Answers 2

6

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.

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

Comments

4

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.

Comments

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.