且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django REST框架:如果相关字段不存在,则在POST上返回404(不是400)?

更新时间:2023-11-30 15:04:34

而不是使用 pre_save 为什么不在你的API视图中覆盖 post

Instead of using pre_save why not override post in your API view:

def post(self, request, *args, **kwargs):
    ...other stuff
    try:
        obj.sample = Sample.objects.get(name=self.request.DATA['sample'])
        ...or whatever other tests you want to do
    except:
        return Response(status=status.HTTP_404_NOT_FOUND)

    response = super(CharacterizationList, self).post(request, *args, **kwargs)
    return response

确保您导入DRF的状态:

Make sure you import DRF's status:

from rest_framework import status

此外,请注意,您可能希望更具体地了解您捕获的异常。 Django的 get 方法将返回 DoesNotExist ,如果没有匹配或 MultipleObjectsReturned 如果多个对象匹配。 相关文档

Also, note you will likely want to be more specific with the Exceptions you catch. Django's get method will return either DoesNotExist if nothing matches or MultipleObjectsReturned if more than one object matches. The relevant documentation:


请注意,使用get()和使用
filter()与slice [ 0]。如果没有匹配
查询的结果,get()将引发一个DoesNotExist异常。这个异常是正在执行查询的模型类的
属性 - 所以在上面的代码中
,如果没有主键为
1的Entry对象,Django将提高Entry.DoesNotExist。

Note that there is a difference between using get(), and using filter() with a slice of [0]. If there are no results that match the query, get() will raise a DoesNotExist exception. This exception is an attribute of the model class that the query is being performed on - so in the code above, if there is no Entry object with a primary key of 1, Django will raise Entry.DoesNotExist.

同样,如果有多个项目匹配
get()查询,Django将会抱怨。在这种情况下,它将引发MultipleObjectsReturn,
,它再次是模型类本身的一个属性。

Similarly, Django will complain if more than one item matches the get() query. In this case, it will raise MultipleObjectsReturned, which again is an attribute of the model class itself.