[英]Specify django-rest-framework field for serializer after request?
I've got the following code: 我有以下代码:
models.py
class Interview(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, help_text="The Primary Key of the Interview")
organization = models.ForeignKey(Organization, on_delete=models.CASCADE, help_text="The Primary Key of the Organization in the interview")
question = name = models.CharField(max_length=200, help_text="The Question")
serializers.py
class InterviewSerializer(serializers.ModelSerializer):
class Meta:
model = Interview
fields = ('organization', 'question')
views.py
class InterviewViewset(viewsets.ModelViewSet):
"""
API endpoint that allows Interviews to be viewed or edited.
"""
serializer_class = InterviewSerializer
Right now, the request body to create an interview requires these fields: 现在,创建采访的请求主体需要以下字段:
{
"organization": "string",
"question": "string"
}
I'd like the organization for the Interview to automatically be set to the current users organization ( request.user.Organization
- I've got a custom User model). 我希望将采访对象的组织自动设置为当前的用户组织(
request.user.Organization
我有一个自定义的User模型)。 How can I do this elegantly for my viewset? 如何为我的视野优雅地做到这一点?
One way (probably the best) is overriding save
/ create
/ update
methods of your ModelSerializer class. 一种方法(可能是最好的方法)是重写ModelSerializer类的
save
/ create
/ update
方法。 DRF docs about it 关于它的DRF文档
There you can use self.context.get("request")
to get current user. 在那里,您可以使用
self.context.get("request")
来获取当前用户。 And if you still need organization
field to be serialized, just make it read_only=True
而且,如果您仍然需要对
organization
字段进行序列化,只需将其设置为read_only=True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.