我正在尝试序列化CreateUserSerializer(ModelSerializer)
我的代码如下。我的问题是它只会创建User
而不是UserProfile
。
models.py
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
"""
Many other attributes like display_name, dob, hometown, etc
"""
serializers.py
class CreateUserProfileSerializer(ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User.objects.create(
validated_data['username'],
validated_data['email'],
validated_data['password'])
user.save()
user_profile = UserProfile(user=user)
user_profile.save()
return user_profile
在我看来,它如下......
api/views.py
class RegistrationAPI(GenericAPIView):
serializer_class = CreateUserProfileSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
return Response({
"user": UserProfileSerializer(user, context=self.get_serializer_context()).data,
})
如果你按照代码,响应将给我一个
" RelatedManager没有属性' pk'"
答案 0 :(得分:0)
将serializer.py
更改为以下
class CreateUserProfileSerializer(ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User.objects.create(**validated_data)
UserProfile.objects.create(user=user)
return user