Django序列化:尝试在序列化程序上获取字段值时的AttributeError

时间:2017-10-16 11:55:45

标签: python django serialization django-rest-framework

我收到以下错误,

  

AttributeError:尝试在序列化程序devicedetails上获取字段DISerializer的值时获得AttributeError。   序列化程序字段可能名称不正确,并且与Device实例上的任何属性或键都不匹配。   原始例外文字是:'设备'对象没有属性' devicedetails'。

我的models.py: -

class DeviceInfo(models.Model):
    vendor = models.CharField(max_length=250)
    device_type = models.CharField(max_length=250)
    modelname = models.CharField(max_length=100)

class Device(models.Model):
    name = models.CharField(max_length=100, primary_key=True)
    username = models.TextField()
    password = EncryptedTextField()
    deviceinfo = models.ForeignKey(DeviceInfo, null=True)

class DeviceDetails(models.Model):
    device = models.ForeignKey(Device)
    serial_number = models.CharField(max_length=100)
    version = models.CharField(max_length=100)

serializer.py: -

class DeviceInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = DeviceInfo
        fields = ("id", "vendor", "device_type", "modelname")

class DeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Device
        fields = ("name","username", "password", "deviceinfo")

class DeviceDetailsSerializer(serializers.ModelSerializer):
    class Meta:
         model = DevieceDetails
         fields = ("device", "serial_number", "version")

class DISerializer(serializers.ModelSerializer):
    deviceinfo = DeviceInfoSerializer(read_only=True)
    devicedetails = DeviceDetailsSerializer(many=True)

    class Meta:
        model = Device
        fields = ("name", "username", "password", "deviceinfo", "devicedetails")

views.py: -

def list(self, request):
    list = Device.objects.all()
    serializer = DISerializer(list, many=True)

1 个答案:

答案 0 :(得分:1)

您需要将devicedetails字段重命名为devicedetails_set。为_set填充的关系自动生成反向名称:

devicedetails_set = DeviceDetailsSerializer(many=True)

或在related_name DeviceDetails's字段使用device

device = models.ForeignKey(Device, related_name='devicedetails')

来自docs

  

如果您没有为反向关系设置相关名称,则需要在fields参数中使用自动生成的相关名称。例如:track_set