使用Django Rest框架在验证步骤之前修改数据 [英] Modify data before validation step with django rest framework
问题描述
我有一个简单的 Model
,其中存储了使用 ForeignKey
创建它的用户。该模型具有对应的 ModelSerializer
和 ModelViewSet
。
I have a simple Model
that stores the user that created it with a ForeignKey
. The model has a corresponding ModelSerializer
and ModelViewSet
.
问题在于,当用户提交 POST
来创建新记录时, user
应该由后端设置。我尝试覆盖 ModelViewSet
上的 perform_create
来设置用户,但实际上在验证步骤中仍然失败(这使得感)。回来时说 user
字段为必填字段。
The problem is that when the user submits a POST
to create a new record, the user
should be set by the backend. I tried overriding perform_create
on the ModelViewSet
to set the user, but it actually still fails during the validation step (which makes sense). It comes back saying the user
field is required.
我正在考虑覆盖 ModelSerializer
上的> user 字段是可选的,但我觉得可能存在更干净,更有效的方法。有什么想法吗?
I'm thinking about overriding the user
field on the ModelSerializer
to be optional, but I feel like there's probably a cleaner and more efficient way to do this. Any ideas?
推荐答案
您可以将 user
字段设置为 read_only。
You can make the user
field as read_only.
这将确保序列化表示形式时使用该字段,而在反序列化期间创建或更新实例时不使用该字段。
This will ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.
在序列化程序中,您可以执行以下操作:
In your serializers, you can do something like:
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
extra_kwargs = {
'user' : {'read_only' : True} # define the 'user' field as 'read-only'
}
然后您可以覆盖 perform_create ()
并根据您的要求设置用户
。
You can then override the perform_create()
and set the user
as per your requirements.
这篇关于使用Django Rest框架在验证步骤之前修改数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!