Home > Blockchain >  DRF, why my root api urls are got mixed (combined)?
DRF, why my root api urls are got mixed (combined)?

Time:01-22

These are my code snippets:

# serializers.py
from rest_framework import serializers
from .models import User


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


class UserActivitySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = (
            'id',
            'email',
            'last_login',
            'last_requested_at',
        )
# urls.py
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'user-activity', UserActivityViewSet)

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

This leads to combined Root API urls, like so: enter image description here

However this is not the expected behavior. I wanted 2 separate urls. First with all users (for example, localhost:8000/users with all users and localhost:8000/users/ for specific user). And second with user activity API. with those 4 fields. I don't have clue why my urls got combined when I added router.register(r'user-activity', UserActivityViewSet) to my urls.py. Please help with broad explanation, if possible. Thanks!

CodePudding user response:

Try to specify the basename to the routes like this:

# urls.py
router = routers.DefaultRouter()
router.register(r'users', UserViewSet, basename="users")
router.register(r'user-activity', UserActivityViewSet, basename="user-activity")

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

PS.: Some DRF versions call that as base_name

  • Related