gpt4 book ai didi

django - 重写CreateAPIView,访问请求用户

转载 作者:行者123 更新时间:2023-12-02 04:56:05 26 4
gpt4 key购买 nike

如何将created_by保存为请求用户?请注意,该字段未在序列化器中定义

class User(models.Model):
email = models.EmailField(...)
name = models.CharField(...)
created_by = models.ForeignKey('User')

class UserSerializer(serializer.ModelSerializer):
class Meta:
model = User
fields = ['email', 'name']

class CreateUserApiView(CreateAPIView):
model = User
serializer_class = CreateRequesterSerializer

def create(self, request, *args, **kwargs):
# how can I save `created_by` as request user?
return super(CreateUserApiView, self).create(request, *args, **kwargs)

最佳答案

重写CreateAPIViewperform_create()方法

class CreateUserApiView(CreateAPIView):
# your code

<b>def perform_create(self, serializer):
serializer.save(created_by=self.request.user)</b>

关于django - 重写CreateAPIView,访问请求用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53221990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com