Django Rest Framework: Access item detail by slug instead of ID -
is possible use object's slug (or other field) access details of item, instead of using id?
for example, if have item slug "lorem" , id 1. default url http://localhost:9999/items/1/
. want access via http://localhost:9999/items/lorem/
instead.
adding lookup_field
in serializer's meta class did nothing change automatically generated url nor did allow me access item manually writing slug instead of id in url.
models.py
class item(models.model): slug = models.charfield(max_length=100, unique=true) title = models.charfield(max_length=100, blank=true, default='') # arbitrary, user provided, url item_url = models.urlfield(unique=true)
serializers.py
class classitemserializer(serializers.hyperlinkedmodelserializer): class meta: model = item fields = ('url', 'slug', 'title', 'item_url')
views.py
class itemviewset(viewsets.modelviewset): queryset = item.objects.all() serializer_class = itemserializer
urls.py
router = defaultrouter() router.register(r'items', views.itemviewset) urlpatterns = [ url(r'^', include(router.urls)), ]
generated json:
[ { "url": "http://localhost:9999/items/1/", "slug": "lorem", "title": "lorem", "item_url": "http://example.com" } ]
you should set lookup_field
in 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 view:
class itemviewset(viewsets.modelviewset): queryset = item.objects.all() serializer_class = itemserializer lookup_field = 'slug'
i got 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/" }
Comments
Post a Comment