我有以下序列化程序:
curl --data-urlencode
我需要验证数据库中是否存在具有id的类别,并在视图中检索它的值。为了避免两次提取class SearchSerializer(serializers.Serializer):
category_id = serializers.IntegerField()
search_term = serializers.CharField(required=False)
,我已将以下Category
添加到序列化程序中。
validate()
但它会导致错误。
def validate(self, data):
try:
category = Category.objects.get(pk=data['category_id'])
except Category.DoesNotExist:
raise serializers.ValidationError('Invalid category_id')
self.data['category'] = category
return data
有办法做到这一点吗?
views.py
When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation.
You should either call `.is_valid()` first, or access `.initial_data` instead.
答案 0 :(得分:2)
而不是self.data['category'] = category
,您只需在data['category'] = category
方法中使用validate
你应该考虑使用PrimaryKeyRelatedField
,如下所示:
category = serializers.PrimaryKeyRelatedField(
queryset=Category.objects.all(),
error_messages={'does_not_exist': 'Invalid category id'})
并且您根本不需要validate
,您可以直接以Category
serializer.validated_data['category']
对象