I’m facing an issue while trying to access deeply nested attributes within the validate
method of a Django Rest Framework serializer. Here’s a simplified version of my serializer:
from rest_framework import serializers
from myapp.models import User
class YourSerializer(serializers.ModelSerializer):
def validate(self, attrs):
if hasattr(self.parent.instance, 'vehicle'):
if hasattr(self.parent.instance.vehicle, 'engine'):
if hasattr(self.parent.instance.vehicle.engine, 'fuel'):
fuel_type = self.parent.instance.vehicle.engine.fuel.diesel
if fuel_type:
pass
else:
raise serializers.ValidationError("Fuel type is not available.")
else:
raise serializers.ValidationError("Fuel attribute is not available.")
else:
raise serializers.ValidationError("Engine attribute is not available.")
else:
raise serializers.ValidationError("Vehicle attribute is not available.")
return attrs
In the validate
method, I’m attempting to access deeply nested attributes (vehicle.engine.fuel.diesel
) of the parent instance.
The thing is Model engine is created after user does ABC operations, and same applies for fuel, and diesel. When a load of people work on
codebase its tough to identify if a these Models are created or not, normally getattr()
and hasattr()
are used, but clubbing these a lot makes
code look messy.
Tried static loots like mypy and pylint, they help to a certain extent but sometimes, TypeError, NoneType issues popup.
Not sure how to fix these.
Thank you for your help!