Issue
class serializer_blahblah(serializers.ModelSerializer):
"""Serializer for ProfileUsefulRecommendations."""
profile_id = serializers.UUIDField()
recommendation_id = serializers.UUIDField()
class Meta:
"""Meta class."""
fields = (
"id",
"profile_id",
...
everything works perfectly with this serializer, however I decided to add object-level validation
Here is what happens:
def validate(self, data):
recommendation_id = str(data["recommendation_id"])
print("recommendation: ", recommendation_id)
validate_recommendation_id(recommendation_id=recommendation_id)
print(validate_recommendation_id(recommendation_id=recommendation_id))
return data
Print out:
recommendation: 3a232d0d-0705-4775-8bae-0e2f3d69c96c
It does not even recognize the function....
However, if I use exactly same function in individual field serializer, it goes well. But shortly speaking I need it as a object-level
ADDED the code of function:
def validate_recommendation_id(recommendation_id):
try:
Recommendation.objects.get(id=recommendation_id)
except Recommendation.DoesNotExist as exception:
raise serializers.ValidationError(
{f"{recommendation_id}": "does not exist"}
) from exception
return recommendation_id
Solution
Actually guys, I have come up with solution as such. Instead of validation function, I defined
Class CheckIfObjectHasId(queryset, lookup_object)
which later I called in serializers:
class serializer_blahblah(serializers.ModelSerializer):
"""Serializer for ProfileUsefulRecommendations."""
profile_id = serializers.UUIDField(
validators=[
CheckIfObjectHasId(queryset=Profile.object.all(), lookup_object="id"
]
)
Answered By - Aleksandre Bregadze
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.