使用序列化器时的关键错误

Key error in work with serializer

models.py:

class Car(models.Model):
    # many fields

class CarOptions(models.Model):
    car = models.OneToOneField(Car, primary_key=True, related_name='options')
    color = models.CharField()
    # many other fields

所以,我想从 Car 及其 CarOptions 获取所有信息。

serializer.py:

class CarOptionsSerializer(serializers.ModelSerializer):
    color = serializers.CharField()

    class Meta:
        model = CarOptions
        fields = ('color')

class CarSerializer(serializers.ModelSerializer):
    color = CarOptionsSerializer(many=True, read_only=True, )

    class Meta:
        model = Car
        fields = ('many fields', 'color', )

views.py中,我在[中基于XMLRenderer创建了class =48=]() 方法 (link) 我使用:

self._to_xml(xml, item["color"])

但是没有用。我有一个错误:

KeyError: 'color'

我打印了item-dict,但里面没有键color

如何解决?

谢谢!

您应该使用 options 字段名称而不是 color 字段名称来引用 CarSerializer 中的选项(因为您设置了相关的OneToOneField 中的 options 字段)。您没有直接在 Car 上定义 color 字段。

以下代码适用于最新的 django 和 rest 框架:

models.py

class CarModel(models.Model):
    name = models.CharField(max_length=250)

class CarOptionsModel(models.Model):
    car = models.OneToOneField(CarModel, related_name='options')
    color = models.CharField(max_length=250)

serializers.py

class CarOptionsSerializer(serializers.ModelSerializer):
    color = serializers.CharField()

    class Meta:
        model = CarOptionsModel
        fields = ('color',)

class CarSerializer(serializers.ModelSerializer):
    options = CarOptionsSerializer(read_only=True, )

    class Meta:
        model = CarModel
        fields = ('options', 'name')

views.py

class CarViewSet(viewsets.ModelViewSet):
    serializer_class = CarSerializer
    queryset = CarModel.objects.all()

urls.py

router = routers.DefaultRouter()
router.register(r'api', CarViewSet)
urlpatterns = router.urls

我会注意到,由于您定义了一对一映射,因此您不能 many=True