django rest框架展开字段属性错误

hwamh0ep  于 2021-09-08  发布在  Java
关注(0)|答案(0)|浏览(200)

我的序列化程序中有展开字段。我发送请求api/drivers/?expand=tractors\uuuuu drivers\uuuuu driver并获取错误:“在尝试获取字段的值时获取attributeerror make 关于序列化程序 TractorSerializer . 序列化程序字段的名称可能不正确,并且与 TractorDriver 例如。原始异常文本为:“tractordriver”对象没有属性“make”
模型:

class Tractor(BaseModel):
    ...
    make = models.CharField("Make", max_length=32)
    ...

class TractorDriver(BaseModel):
    tractor = models.ForeignKey(
        Tractor,
        verbose_name="Tractor",
        on_delete=models.CASCADE,
        related_name="drivers",
    )
    driver = models.ForeignKey(
        Driver,
        verbose_name="Driver",
        on_delete=models.CASCADE,
        related_name="tractors",
    )
    ...

序列化程序:

class DriverSerializer(BaseModelSerializer):
    class Meta:
        model = Driver
        expandable_fields = dict(
            ...
            tractors=dict(
                serializer="safety.api.serializers.TractorSerializer", many=True,
            ),
            ...
class TractorDriverSerializer(BaseModelSerializer):
    class Meta:
        model = TractorDriver
        expandable_fields = dict(
            tractor=dict(serializer="safety.api.serializers.TractorSerializer", read_only=True),
            driver=dict(serializer="safety.api.serializers.DriverSerializer", read_only=True),
        )
class TractorSerializer(BaseModelSerializer):
    class Meta:
        model = Tractor
        expandable_fields = dict(
            ...
            drivers=dict(
                serializer="safety.api.serializers.TractorDriverSerializer", many=True,
            ),
            ...

意见:

class DriverStatusViewSet(BaseModelViewSet):
    queryset = DriverStatus.objects.all()
    serializer_class = DriverStatusSerializer

class TractorViewSet(BaseModelViewSet):
    queryset = Tractor.objects.all()
    serializer_class = TractorSerializer

class TractorDriverViewSet(BaseModelViewSet):
    queryset = TractorDriver.objects.all()
    serializer_class = TractorDriverSerializer
``` `TractorDriver` 示例没有 `make` 领域 `Tractor` 示例包含 `make` 领域我不明白它为什么要找我 `make` 野外 `TractorDriver` 例如。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题