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 "lorem" and ID 1. By default the URL is http://localhost:9999/items/1/
. I want to access it via http://localhost:9999/items/lorem/
instead.
Adding lookup_field
in the serializer's Meta class did nothing to change the automatically generated URL nor did it allow me to access the item by manually writing the slug instead of the ID in the URL.
models.py
class Item(models.Model):
slug = models.CharField(max_length=100, unique=True)
title = models.CharField(max_length=100, blank=True, default='')
# An 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"
}
]
In some scenarios you may want to have both the "low level"
pk
value and the more semanticslug
. I like to have both options personally and do this by setting thelookup_field
later in the viewsetas_view()
method in myurls.py
.You should set
lookup_field
in your serializer:and in your view:
I got this result: