每个请求方法在drf序列化程序中的不同验证 [英] different validation in drf serializer per request method
问题描述
让我们说我有一个像这样的模型:
Lets say i have a model like so:
class MyModel(models.Model):
first_field = models.CharField()
second_field = models.CharField()
和类似API的视图因此:
and an API view like so:
class MyModelDetailAPI(GenericAPIView):
serializer_class = MyModelSerializer
def patch(self, request, *args, **kwargs):
# Do the update
def post(self, request, *args, **kwargs):
# Do the post
first_field
是仅在POST方法中插入的字段(并且是强制性的),但每次更新时,用户都无法更改其值,因此PATCH方法中的字段是非强制性的。
如何编写序列化程序,以便 first_field
在POST上是必需的,而在PATCH上则不是必需的。有什么方法可以动态设置必填字段,以便我仍然可以使用DRF验证机制?每个请求方法都使用某种验证程序分派器?
我想要这样的例子:
The first_field
is a field that is only inserted in the POST method (and is mandatory) but on each update, the user can't change its value so the field in the PATCH method is not mandatory.
How can i write my serializer so that the first_field
is required on POST but not required on PATCH. Is there any way of dynamically setting the required field so i can still use the DRF validation mechanism? Some sort of validator dispatcher per request method?
I want something like this for example:
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = {
'POST': ['first_field']
'PATCH': []
}
推荐答案
我需要的空间比注释所提供的更多,以使我的意思清楚。所以这是我的建议:
I need more space than comments provide to make my meaning clear. So here is what I suggest:
-
不同的格式意味着不同的序列化器。
Different formatting means different serializers.
因此,这里有一个 MyModelSerializer
和一个 MyModelCreationSerializer
。要么独立创建它们,要么让一个继承另一个并将其专门化(如果有意义)。
So here you have, for instance a MyModelSerializer
and a MyModelCreationSerializer
. Either create them independently, or have one inherit the other and specialize it (if it makes sense).
使用适当的 GenericAPIView
挂钩返回正确的序列化器类,具体取决于 self.action
。一个非常基本的示例可能是:
Use the appropriate GenericAPIView
hook to return the correct serializer class depending on self.action
. A very basic example could be:
class MyModelDetailAPI(GenericAPIView):
# serializer_class = unneeded as we override the hook below
def get_serializer_class(self):
if self.action == 'create':
return MyModelCreationSerializer
return MyModelSerializer
常规视图集中的默认操作已记录在此处,它们是:
Default actions in regular viewsets are documented here, they are:
-
create
:基本路线url上的POST方法 -
list
:基本路线url上的GET方法 -
检索
:对象URL的GET方法 -
update
:对象URL上的PUT方法 -
partial_update
:对象URL上的PATCH方法 -
destroy
:对对象网址删除方法
create
: POST method on base route urllist
: GET method on base route urlretrieve
: GET method on object urlupdate
: PUT method on object urlpartial_update
: PATCH method on object urldestroy
: DELETE method on object url
这篇关于每个请求方法在drf序列化程序中的不同验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!