Django rest框架仅创建序列化器字段 [英] Django rest framework create-only serializer field
问题描述
我有一个Django模型作为请求描述。创建它是为了由REST客户端发出请求,用于记录任务的当前状态,并记录客户端收到的历史请求。
I'm have a Django model that serves as a request description. It is created to issue a request by a REST client, serves to record the tasks current status, and record historical requests received by clients.
此模型具有一些字段,用于微调和控制所请求的任务(例如,目标对象和操作类型)。显然,我希望客户端在创建对象时控制这些字段,但此后不要控制(一旦任务开始运行就无法更改对象)。
This model has a few fields that are used to fine-tune and control the requested task (say, a target object and the type of action). Obviously, I'd like the client to control those fields on object creation but not afterwards (you can't change the object once the task started running).
希望找到类似于 serializers.ReadOnlyField
的东西,所以我可以有类似的东西:
I was hoping for something similar to serializers.ReadOnlyField
, so I could have something similar to this:
class TaskSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
task_id = serializers.ReadOnlyField()
target_object = serializers.CreateOnlyField()
,但在文档或Google中找不到它。
but couldn't find it in the documentation or google.
推荐答案
只是扩展Wim的答案,这是一种基于传入请求方法选择其他序列化程序的方法:
Just to expand on Wim's answer, this is a way to select a different serialiser based on the incoming request method:
class RequestViewSet(viewsets.ModelViewSet):
serializer_class = RequestModelSerializer
model = Request
def get_serializer_class(self):
serializer_class = self.serializer_class
if self.request.method == 'POST':
serializer_class = SerializerWithoutCertainFields
return serializer_class
这篇关于Django rest框架仅创建序列化器字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!