尝试获取字段值时出现AttributeError

时间:2019-04-16 12:46:05

标签: django django-rest-framework

**试图从一个端点创建两个对象(无嵌套序列化器)时。我有一个错误 错误:  / migratestudent的AttributeError 尝试获取序列化程序registration_no上字段StudentDataMigrateSerializer的值时,出现AttributeError。 序列化程序字段的名称可能不正确,并且与Student实例上的任何属性或键都不匹配。 原始异常文本为:'Student' object has no attribute 'registration_no'

class Student(models.Model):
    name = models.CharField(max_length=300)
    sex  = models.CharField(choices=SEX_CHOICES,max_length=255, null=True)
    Category = models.CharField(max_length=100, null=True)

    def __str__(self):
        return self.name


class Registration(models.Model):
    registration_no = models.CharField(max_length=255, unique=True)
    student = models.OneToOneField(Student, 
    on_delete= models.CASCADE, related_name='registration')

    def __str__(self):
    return self.registration_no

class StudentDataMigrateSerializer(serializers.Serializer):

    name = serializers.CharField()
    sex = serializers.CharField()
    registration_no = serializers.CharField()
    #registration_no = serializers.CharField()


    def create(self,validated_data):
        name = validated_data.pop('name')
        sex = validated_data.pop('sex')
        registration_no= validated_data.pop('registration_no')
        #registration_no = validated_data.pop('registration_no')
        #check for existence of registration number

        #Student.objects.CheckRegistration(name, '4')

        try:
            regn = Registration.objects.get('registration_no')
        except:
            student = Student.objects.create(name=name, sex=sex)
            registration = Registration.objects.create(
                    registration_no=registration_no,
                    student=student)

        return student

class StudentDataMigrateCreateAPIVIew(ListCreateAPIView):
    serializer_class= StudentDataMigrateSerializer

    def get_queryset(self):
        student = Student.objects.all()
        return student

1 个答案:

答案 0 :(得分:0)

您正在序列化程序上定义以下字段:

class StudentDataMigrateSerializer(serializers.Serializer):
    name = serializers.CharField()
    sex = serializers.CharField()
    registration_no = serializers.CharField()

并在您的student方法中返回create对象:

    def create(self,validated_data):
        ...
        return student

向该端点发出发布请求时,StudentDataMigrateCreateAPIVIew正在使用请求数据创建并验证序列化器(StudentDataMigrateSerializer)。如果验证通过,它将调用序列化器的create方法。到目前为止一切都还好。创建实例后,视图还必须返回响应。因此它返回序列化程序的data属性。

在这一点上,serializer.data实际上是您在create方法中返回的学生对象的表示。您的序列化程序尝试根据其中定义的字段返回表示形式。

这些是您在序列化时定义的字段:namesexregistration_no。但是Student模型,因此student对象没有registration_no字段。因此,您的序列化程序尝试在student对象上获取此字段时会失败。

您可以将registration_no字段设为write_only,以使其不会作为响应返回。

class StudentDataMigrateSerializer(serializers.Serializer):
    name = serializers.CharField()
    sex = serializers.CharField()
    registration_no = serializers.CharField(write_only=True)