Hassam Ali
Hassam Ali

Reputation: 181

DRF Newbie - Stuck in small mistake kindly assist

I created 1 API its all working fine from all ends. I created 2nd API the DRF headings title showing the headings of old api where i am doing mistake kindly assist.

serializers.py

from rest_framework import serializers
from .models import Brand, Category


class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = (
            'id',
            'name',
            'slug',
            'icon',
            'featured_image',
            'url'
        )

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = (
            'id',
            'name',
            'slug',
            'featured_image',
        )

products.url

router = routers.DefaultRouter()
router.register(r'', BrandViewSet)
router.register(r'', CategoryViewSet)

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

product.view

class CategoryViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
    """
    API endpoint that allows sites to be viewed or edited
    """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

There is no error but in brower when i run the API url it shows brand list instead of category list,

enter image description here

Upvotes: 0

Views: 51

Answers (1)

Enthusiast Martin
Enthusiast Martin

Reputation: 3091

The problem is that you have the views registered to the same endpoint. So it resolves the first one it finds.

So do the register to different endpoints like this:

router = routers.DefaultRouter()
router.register(r'brands', BrandViewSet)
router.register(r'categories', CategoryViewSet)

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

So you can access brands via 127.0.0.1:8000/brands and categories via 127.0.0.1:8000/categories

Upvotes: 1

Related Questions