get() returned more than one Product -- it returned 2 Django Rest Framework

Viewed 261

DRF returning this: get() returned more than one Product -- it returned 2!, when im trying to get objects from my DB by PK

Serializers

class ProductSerializer(serializers.ModelSerializer):
    # cat_id = serializers.SlugRelatedField(slug_field='cat_id', read_only=True)

    class Meta:
        model = Product
        fields = ('name', 'description', 'cat_id', 'use', 'diametr', 'len', 'color', 'photo')

Views

class CategoryProductView(APIView):
    def get(self, request, pk):
        product = Product.objects.get(cat_id=pk)
        serializer = ProductSerializer(product)
        return Response(serializer.data)

Urls path('api/categorylist/<int:pk>', CategoryProductView.as_view())

1 Answers

If you want to serialize all items belonging to a certain primary key of a category, you filter, and serialize many=True items, so:

class CategoryProductView(APIView):
    
    def get(self, request, pk):
        products = Product.objects.filter(cat_id=pk)
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)
Related