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)