在尝试创建嵌套对象时,我得到此错误。我可能用错关系了;需要您的专业指导。
Cannot assign "OrderedDict([('color', 'black), ('transmission', 'auto'), ('mileage', '20kmpl')])": "Vehicle.detail" must be a "Detail" instance
Django = = 4.1.7Python 3.9.13
期待
{
"auto_id": "some-uuid",
"vehicle": [
{
"manufacturer": "toyota",
"year": 2020,
"detail": {
"color": "black",
"transmission": "auto",
"mileage": "20kmpl"
}
}
]
}
模型class Auto(models.Model):
auto_id = models.UUIDField(primary_key=True)
class Detail(model.Model):
color = models.CharField(max_length=10)
transmission = models.CharField(max_length=10)
mileage = models.CharField(max_length=10)
class Vehicle(models.Model):
manufacturer = models.CharField(max_length=10)
year = models.PostiveIntegerField()
auto = models.ForeignKey(Auto, related_name='vehicle', on_delete=models.cascade)
detail = models.ForeignKey(Detail, on_delete=models.cascade)
序列化器
class DetailSerializer(serializers.ModelSerializer):
class Meta:
model = Detail
fields = ('color', 'transmission', 'mileage')
class VehicleSerializer(serializers.ModelSerializer):
detail = DetailSerializer()
class Meta:
model = Vehicle
fields = ('manufacturer', 'year', 'detail')
class AutoSerializer(serializers.ModelSerializer):
vehicle = VehicleSerializer(many=True)
class Meta:
model = Auto
fields = '__all__'
def create(self, validated_data):
vehicle_list = validated_data.pop('vehicle')
auto = Auto.objects.create(**validated_data)
for vehicle in vehicle_list:
Vehicle.objects.create(auto=auto, **vehicle)
return auto
你能告诉我,我在哪里可以将有序的字典转换为详细的实例吗?
在AutoSerializer
中,您还必须将详细数据作为Detail
对象单独处理,就像您对Auto
和Vehicle
所做的那样:
def create(self, validated_data):
vehicle_list = validated_data.pop('vehicle')
auto = Auto.objects.create(**validated_data)
for vehicle in vehicle_list:
# Pop the detail data
detail_data = vehicle.pop("detail")
# Build detail object
detail = Detail.objects.create(**detail_data)
# Assign the FKs
Vehicle.objects.create(auto=auto, detail=detail, **vehicle)
return auto