【发布时间】:2018-05-06 20:45:22
【问题描述】:
我正在尝试序列化 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'"
【问题讨论】:
标签: django django-models django-rest-framework