'QuerySet'对象在Model Serializer中没有属性'phone'

时间:2019-03-20 09:40:46

标签: django-rest-framework django-serializer

我正在使用Django rest Api构建项目。我有一个名为DriverProfile的模型,现在我必须添加一个driverprofile,但是下面出现错误:

尝试获取字段phone的值时出现AttributeError      在序列化程序DriverProfileCreateSerializer上。序列化程序字段的名称可能不正确,并且与QuerySet实例上的任何属性或键都不匹配。原始异常文本为:'QuerySet'对象没有属性'phone'

我已经使用了APIView和modelSerializer,但当驱动程序配置文件中包含电话字段时,我不知道为什么要使用它。 当我从通用视图而不是APIView执行此操作时很重要,但它可以工作,但是当我使用模型序列化器和API视图时会引发错误。我猜错误是在模型序列化器的create()中,我在其中使用driverprofile = DriverProfile.objects.all (),我无法排序,请其他人指导。

Models.py:

class Driver(models.Model):
    User=models.ForeignKey(User,on_delete=models.CASCADE)
    objects = models.Manager()

class DriverProfile(models.Model):
    driver=models.OneToOneField(Driver,on_delete=models.CASCADE)
    drive_name=models.CharField(max_length=20,blank=True)
    phone=models.CharField(max_length=12)
    driver_cnic=models.CharField(max_length=13)

Views.py

class CreateDriverProfile(APIView):

    def get(self,request):
        return Response([DriverProfileCreateSerializer(driver).data for driver in DriverProfile.objects.all()])

    def post(self,request):
        payload=request.data
        serializer=DriverProfileCreateSerializer(data=payload)

        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.py:

class DriverProfileCreateSerializer(serializers.ModelSerializer): # create driver profile

    class Meta:
        model=DriverProfile
        fields = '__all__'

    def create(self, validated_data):
        driverprofile = DriverProfile.objects.all()
        return driverprofile

    def update(self, instance, validated_data):
        for k, v in validated_data.items():
            setattr(instance, k, v)
            instance.save()
        return instance

1 个答案:

答案 0 :(得分:1)

  • 像这样更改您的DriverProfileCreateSerializer
class DriverProfileCreateSerializer(serializers.ModelSerializer): # create driver profile

    class Meta:
        model=DriverProfile
        fields = '__all__'

    def create(self, validated_data):
        driverprofile = DriverProfile.objects.create(**validated_data) # HERE!
        return driverprofile

    def update(self, instance, validated_data):
        for k, v in validated_data.items():
            setattr(instance, k, v)
            instance.save()
        return instance