Django-REST-Framework: ForeignKey instance is not passed to validated_data

天大地大妈咪最大 提交于 2021-02-11 13:28:58

问题


I'm trying to create an instance overriding create method and passing the ForeignKey instance in the data, but that field is not included in validated_data passed to create method. How can I pass that to create ??

I have this model.

class UserProfile(models.Model):
    name = models.CharField(verbose_name='Name', max_length=50)
    email = models.EmailField(verbose_name='Email')
    address = models.TextField(verbose_name='Address', null=True, blank=True)
    user = models.OneToOneField(User, verbose_name='User', on_delete=models.CASCADE)

And here's my serializer.

class UserProfileSerializer(ModelSerializer):
    class Meta:
        model = UserProfile
        fields = '__all__'
        depth = 2

    def create(self, validated_data):
        print(validated_data)
        return UserProfile.objects.create(**validated_data)

Here's my view.

class UserRegisterView(APIView):
    def post(self, request, format=None, *args, **kwargs):
        name = request.data.get('name')
        email = request.data.get('email')
        password = request.data.get('password')
        address = request.data.get('address')

        if name and email and password:
            user = User.objects.create_user(username=email, password=password, email=email)

            request.data['user'] = user
            serializer = UserProfileSerializer(data=request.data)
            if serializer.is_valid():
                user_profile = serializer.save()

Even though I'm passing User object to serializer it's not included in the validated_data. Official doc suggests to create another serializer for User model and use that, but is there any other way without creating that serializer ??


回答1:


You can pass it as additional argument of save method:

serializer = UserProfileSerializer(data=request.data)
if serializer.is_valid():
    user_profile = serializer.save(user=user)

From the docs:

Any additional keyword arguments will be included in the validated_data argument when .create() or .update() are called.



来源:https://stackoverflow.com/questions/52297171/django-rest-framework-foreignkey-instance-is-not-passed-to-validated-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!