无法在create()方法中使用.pop('field')从序列化程序中删除字段 - DRF

时间:2018-02-01 12:21:19

标签: python django django-rest-framework

我正在使用Django休息框架。我想创建管理端点,用户可以在其中添加具有项目权限的成员。以下是来自用户的数据。

{
  "email" : "name@yopmail.com",
  "first_name" : "asd",
  "last_name" : "asd",
  "projects":[{
     "project_id" : 1,
     "project_role" : 1 },
   { "project_id" : 1,
     "project_role" : 1
  }],
  "position" : "something something"
}

以下是我创建的用于验证和保存数据的序列化程序。

class ProjectPermissionSerializer(serializers.Serializer):
    """
        Serialiser to hold permissions pair of project_id and role
    """
    project_id = serializers.IntegerField(allow_null=False)
    project_role = serializers.ChoiceField(PROJECT_ROLES)

    def create(self, validated_data):
        print(validated_data)

    def update(self, instance, validated_data):
        pass


class ProjectMemberSerializer(serializers.ModelSerializer):
    """
        serializer to add new member with projects
    """

    projects = ProjectPermissionSerializer(many=True)
    email = serializers.EmailField()

    class Meta:
        model = User
        fields = ('first_name',  'last_name', 'email', 'position', 'projects')

    def create(self, validated_data):
        permission_data = validated_data.pop('projects')
        emailstatus = {"email_id": validated_data.pop('email')}
        emailobj, created = EmailStatus.objects.get_or_create(**emailstatus)
        validated_data['email'] = emailobj
        project_member = User.objects.create(**validated_data)
        return project_member

仍然,在从validated_data弹出项目后,我收到了以下错误。

AttributeError: Got AttributeError when attempting to get a value for field `projects` on serializer `ProjectMemberSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'projects'.

1 个答案:

答案 0 :(得分:0)

看起来您的模型没有字段命名项目,在这种情况下您需要指定字段的来源,以将序列化程序的字段与模型的字段链接,例如'project_set':

 projects = ProjectPermissionSerializer(many=True, source='project_set')