Django Rest Framework: Access item detail by slug instead of ID

后端 未结 2 1162
我在风中等你
我在风中等你 2020-12-08 06:58

Is it possible to use a object\'s slug (or any other field) to access the details of an item, instead of using the ID?

For example, if I have an item with the slug \

2条回答
  •  心在旅途
    2020-12-08 07:02

    You should set lookup_field in your serializer:

    class ItemSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = Item
            fields = ('url', 'slug', 'title', 'item_url')
            lookup_field = 'slug'
            extra_kwargs = {
                'url': {'lookup_field': 'slug'}
            }
    

    and in your view:

    class ItemViewSet(viewsets.ModelViewSet):
        queryset = Item.objects.all()
        serializer_class = ItemSerializer
        lookup_field = 'slug'
    

    I got this result:

    ~ curl http://127.0.0.1:8000/items/testslug/ | python -mjson.tool
    {
        "item_url": "https://example.com/", 
        "slug": "testslug", 
        "title": "Test Title", 
        "url": "http://127.0.0.1:8000/items/testslug/"
    }
    

提交回复
热议问题