如何将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)
答案 0 :(得分:4)
覆盖 CreateAPIView
的perform_create()
方法
class CreateUserApiView(CreateAPIView):
# your code
def perform_create(self, serializer):
serializer.save(created_by=self.request.user)