Python rest_framework how to change URL?

Asked

Viewed 87 times

0

How can I change the urls in rest_framework on Django?

The router defaults to using the creature ID in the URL ex. /api/Creatures/1/

I want instead of appearing the ID, appear the name of the creature.

ex. /api/Creature/dragon/

serializer.py

class CreatureSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Creature
        fields = ['url', 'name', 'experience', 'level', 'description', 'resistance', 'drop', 'rare_drop']

py router.

router = routers.DefaultRouter()
router.register(r'creatures', CreatureViewSet, basename='creature')

urlpatterns = [
    path('', include(router.urls)),
]

1 answer

2


In "views.py" in the class definition it should be something like CreatureViewSet() you must put the attribute lookup_field with the value of the field you want to use:

class CreatureViewSet(...):
    ...
    lookup_field = "name"
    ...

Then you will get access from the name, that is, instead of "/api/pizza/3" you will use "/api/pizza/pepperoni".

Tip: Create a field of Slug to keep the name instead of using the name as reference since "Calabresa" and "Calabresa" will not be the same thing.

  • Where do I put this Lug field? In the Viewset itself?

  • Could not resolve URL for hyperlinked Relationship using view name "Creature-Detail". You may have failed to include the Related model in your API, or incorrectly configured the lookup_field attribute on this field. to with this problem now

Browser other questions tagged

You are not signed in. Login or sign up in order to post.