class serializer_blahblah(serializers.ModelSerializer):
"""Serializer for ProfileUsefulRecommendations."""
profile_id = serializers.UUIDField()
recommendation_id = serializers.UUIDField()
class Meta:
"""Meta class."""
fields = (
"id",
"profile_id",
...
这个序列化程序一切都很好,但是我决定添加对象级验证
下面是发生的事情:
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
打印输出:
recommendation: 3a232d0d-0705-4775-8bae-0e2f3d69c96c
它甚至不认识这个功能
然而,若我在单独的字段序列化程序中使用完全相同的函数,它会很好。但简而言之,我需要它作为一个对象级
增加了功能代码:
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
这就是为每个字段添加验证的方法。
class serializer_blahblah(serializers.ModelSerializer):
recommendation_id = serializers.UUIDField()
def validate_recommendation_id(self, recommendation_id):
return recommendation_id
您不会在validate
方法中调用它。
实际上,伙计们,我已经想出了这样的解决方案。我定义了,而不是验证功能
Class CheckIfObjectHasId(queryset, lookup_object)
后来我调用了序列化程序:
class serializer_blahblah(serializers.ModelSerializer):
"""Serializer for ProfileUsefulRecommendations."""
profile_id = serializers.UUIDField(
validators=[
CheckIfObjectHasId(queryset=Profile.object.all(), lookup_object="id"
]
)