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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With