Django - 多对多字段的嵌套序列化

时间:2018-01-20 12:50:20

标签: django django-rest-framework

我正在尝试创建API,但序列化程序失败了。 我无法弄清楚出了什么问题。

查看:

elif request.method == 'POST':
    data = { 'user':request.data.get('user'),'skill_item':request.data.get('new_user_skill')}
    serializer = UserSkillSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)  

Serializer:

    class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email')
        extra_kwargs = {
            'username': {
                'validators': [UnicodeUsernameValidator()],
            }
        }    


class UserProfileSerializer(serializers.ModelSerializer):
    skill_item =SkillSerializer(read_only=True,many=True) 
    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email','skill_item')
        extra_kwargs = {
            'username': {
                'validators': [UnicodeUsernameValidator()],
            }
        }   

        def create(self, validated_data):

            user = UserModelSerializer.create(UserModelSerializer(),username=validated_data.get('username'))
            user.save()

            UserProfile.objects.create(user=user, user_skills=skill_item)
            return user

class UserSkillSerializer(serializers.ModelSerializer):
    user = UserProfileSerializer(required=True)
    skill_item = SkillSerializer(required=True)
    class Meta:
        model = UserSkill
        fields= '__all__'

    def create (Self,validated_data):
        user_data = validated_data.pop('user')
        user = UserProfileSerializer.create(UserProfileSerializer(),validated_data=user_data)
        skill_data = validated_data.pop('skill_item')
        skill = SkillSerializer.create(SkillSerializer(),validated_data=skill_data)
        user_skill, created = UserSkill.objects.update_or_create(user=user,skill_item=skill_item)

        return user_skill
class SkillSerializer(serializers.ModelSerializer):

    class Meta:
        model = Skill
        fields = '__all__'
        extra_kwargs = {
            'skill_name': {
                'validators': [UnicodeUsernameValidator()],
            }
        } 

型号:

# This class will more or less map to a table in the database and defines skills at the application level
class Skill (models.Model):
    # this defines a required name that cannot be more than 100 characters.
    skill_name = models.CharField(max_length=100,unique=True)
    class Meta:
        app_label = "wantedly_webapp"

# This class will more or less map to a table in the database and defines the many to many relationship between user-skill, this is our intermediate model
class UserSkill(models.Model):
    """ A Model for representing skill in user profile """
    unique_together = (('user', 'skill_item'),)

    user = models.ForeignKey('UserProfile',on_delete=models.CASCADE,related_name='current_user_skills')

    skill_item = models.ForeignKey(Skill,on_delete=models.CASCADE)

    def __str__(self):
        """Return a human readable representation of the model instance."""
        return "{}".format(self.skill_item.skill_name)

# this class adds a Many to Many field in existing django-rest auth UserProfile class for  user and his/her skills 
class UserProfile(models.Model):
    user = models.OneToOneField('auth.User',unique=True,on_delete=models.CASCADE,related_name='user_profile')
    user_skills = models.ManyToManyField(
            Skill,
            through='UserSkill',
            through_fields=('user','skill_item')
        )

我得到的错误基本上是因为我对视图的错误请求而发生错误

  

serialzer.is_valid()

我不确定为什么我的UserProfileSerialzer无法正确序列化。

编辑1

我现在面临以下错误:

    {
        "user": {
            "non_field_errors": [
                "Invalid data. Expected a dictionary, but got User."
            ]
        },
        "skill_item": {
            "non_field_errors": [
                "Invalid data. Expected a dictionary, but got Skill."
            ]
        }

}

我相信这种情况正在发生,因为我的Serializer无法处理外键和多对多关系的嵌套关系。

编辑2 - 我现在面临以下错误 -

 File "C:\code\django\wantedly\src\wantedly_webapp\serializers\UserSkillSerializer.py", line 49, in create
   user = UserProfileSerializer.create(UserProfileSerializer(),validated_data=user_data)
  

/ api / v1 / user / skills / UNIQUE约束中的IntegrityError失败:   auth_user.username

1 个答案:

答案 0 :(得分:1)

我认为您的问题不在serializer.is_valid()行,而在于尝试在下方呈现错误的问题:

return Response({serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

这会失败,因为serializer.errorsReturnDict,而您正尝试使用{}语法创建一组。{1}}改为使用:

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)