我该如何将 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)
created_by
是必填字段,那么这个if语句的作用是什么?如果在post请求中没有这个字段,那么在到达perform_create()
之前就会验证失败。 - Carsten