覆盖CreateAPIView,访问请求用户

时间:2018-11-09 08:14:04

标签: django django-rest-framework

如何将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)

1 个答案:

答案 0 :(得分:4)

覆盖 CreateAPIView

perform_create() 方法
class CreateUserApiView(CreateAPIView):
    # your code

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)