gpt4 book ai didi

python - 如何引发错误/返回 {"foo": ["This field is required."]} response in Django REST

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:10 25 4
gpt4 key购买 nike

假设我有一个 View ,我需要在调用 serializer.save 之前检查是否给定了一个字段,以确保我不会收到字典键错误:

class BarView(CreateAPIView):
serializer_class = BarSerializer
queryset = Bar.objects.all()
def perform_create(self, serializer):
if 'foo' not in self.request.data:
raise ParseError('foo field required.')
foo = get_object_or_404(Foo, pk=self.request.data['foo'])
if foo.counter == 10:
raise ParseError('foo limit reached.')
return serializer.save(user=self.request.user, foo=foo)

而不是返回 "foo field required." 我想返回一条与 Django REST 返回相同的消息,例如{"foo":["此字段为必填项。"]}

有更好的方法吗?也许单独使用序列化程序验证 foo 字段?

更新:我忘了说用户字段也是必需的。

Bar 的模型是:

class Bar(models.Model):
user = models.ForeignKey(User, db_index=True, editable=False)
foo = models.ForeignKey(Foo, db_index=True)

最佳答案

是的,

简单看文档:Validation

(我假设字段 fooBar 模型的一部分,如果不是,请将它添加到 中的 fields):

向 BarSerializer 添加验证:

class BarSerializer(serializers.ModelSerializer):
def validate_foo(self, value):
if not value:
raise serializers.ValidationError("foo field required.")
if Foo.objects.filter(pk=value, counter__gte=10).exists():
raise serializers.ValidationError("foo limit reached.")
return value

class Meta:
model = Bar

然后通过扩展这个来创建你的 View :

from rest_framework.exceptions import ValidationError

class MyCreateAPIView(CreateAPIView):
def post(self, request, *args, **kwargs):
try:
return super(BarView, self).post(request, *args, **kwargs)
except ValidationError as e:
return Response(e.detail, , status=status.HTTP_400_BAD_REQUEST)

def create(self,request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
self.perform_create(serializer)
except DjangoValidationError as e:
raise ValidationError(e.messages)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

def perform_create(serializer):
# do your stuff
serializer.save()

关于python - 如何引发错误/返回 {"foo": ["This field is required."]} response in Django REST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32401599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com