我收到以下錯誤時,Django的序列化:AttributeError的試圖獲得價值領域的串行
AttributeError: Got AttributeError when attempting to get a value for field
devicedetails
on serializerDISerializer
. The serializer field might be named incorrectly and not match any attribute or key on theDevice
instance. Original exception text was: 'Device' object has no attribute '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)
你'DISerializer.devicedetails'屬性呢沒有指定'source'參數。這意味着默認行爲將被調用 - 在'Device'對象上通過該名稱查找屬性。 – Kendas