Django休息框架 - 超链接非模型序列化器字段

时间:2016-02-24 12:34:01

标签: python django django-rest-framework

我正在努力弄清楚如何为非模型查询集实现超链接关系。我有一个观点:

class GGGViewSet(viewsets.ViewSet):

    def list(self, request):
        serializer_class = manufacture_serializer(ar)
        serializer = serializer_class(
            instance = sample.values(), many=True
        )
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        try:
            anobject = sample[pk]
        except KeyError:
            return Response(status=status.HTTP_404_NOT_FOUND)
        except ValueError:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        serializer_class = manufacture_serializer(ar)
        serializer = serializer_class(instance=anobject)

        return Response(serializer.data)

我试图将/ data / trait /的值资源渲染为链接,其中:

性状列表

data/trait/
{
    "value": 12334,
    "another_value": 45672, 
}

性状细节

data/trait/value/

{   
    "value":12334
}

尝试:

url = serializers.HyperlinkedIdentityField(view_name='trait-list')

错误:/ asvo / data / trait /'AObj'对象的AttributeError没有属性'pk'。

任何关于最佳方法的想法都将受到赞赏。 :)

1 个答案:

答案 0 :(得分:0)

你可能非常接近。根据提供的信息,这里展示了HyperlinkedIdentityField使用的东西,而不依赖于实际的Django模型。在填写你的建筑细节时,我不得不用我的想象力。

from rest_framework import routers
from rest_framework import serializers
from rest_framework import status
from rest_framework import viewsets
from rest_framework.response import Response


# This goes in the URL routing file
router = routers.DefaultRouter()
router.register(r'trait', GGGViewSet, base_name='trait')
urlpatterns = router.urls


# The "model"
class Thing(object):
    def __init__(self, pk, value, another_value):
        self.pk = pk
        self.value = value
        self.another_value = another_value


# The "queryset"
sample = {
    '1': Thing(1, 12334, 45672),
    '2': Thing(2, 12335, 45673),
    '3': Thing(3, 12336, 45674)
}


# The serializer
class manufacture_serializer(serializers.Serializer):
    pk = serializers.HyperlinkedIdentityField(
        view_name='trait-detail', read_only=True)
    value = serializers.IntegerField()
    another_value = serializers.IntegerField()

    class Meta:
        fields = ['pk', 'value', 'another_value']


# The view
class GGGViewSet(viewsets.ViewSet):

    def list(self, request):
        serializer = manufacture_serializer(
            instance=sample.values(), many=True, context={'request': request})
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        try:
            anobject = sample[pk]
        except KeyError:
            return Response(status=status.HTTP_404_NOT_FOUND)
        except ValueError:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        serializer = manufacture_serializer(
            instance=anobject, context={'request': request})

        return Response(serializer.data)

我没有完全理解有关data/trait/data/trait/value/的问题的后半部分,但希望这足以让您继续前进。

干杯!