我如何在ModelSerializer中返回id?

时间:2016-12-24 10:40:36

标签: django django-rest-framework

我使用django rest框架ModelSerializer类。我需要返回序列化器模型 LookupRequest

的id
class HistorySerializer(serializers.ModelSerializer):
    vehicle = serializers.SerializerMethodField()
    ...

    def get_vehicle(self, obj):
        instance = models.Vehicle.objects.get(id=obj['vehicle'])
        return VehicleSerializer().to_representation(instance=instance)

    ...

    class Meta:
        model = models.LookupRequest
        fields = ['id', 'vehicle', ...]

id 值并未在get请求中返回。也许有人知道我如何能够返回id。谢谢你的帮助。

我有结果:

{"count":1,"next":null,"previous":null,"results":
    [{
        "vehicle":{...},
        "last_time":"2016-12-24T10:47:20.427Z",
        "has_changed":false
    }]
}

0 个答案:

没有答案