Rahul Sharma
Rahul Sharma

Reputation: 2495

Get Object by pk in URL in Django Rest Framework

I want to retrieve objects from the ORM by the "pk" in URL. Here's what I am trying

This is my Url:

path('api/dispatchhistoryitem/<int:pk>/', views.dispatchhistoryitemsview.as_view(), 'dispatchhistoryitem'),

Views.py

class dispatchhistoryitemsview(ListAPIView):
    queryset = ItemBatch.objects.all()
    serializer_class = holdSerializer

    def get(self, request, pk, *args, **kwargs):
        items = get_object_or_404(ItemBatch, id=self.kwargs.get('pk'))
        serializer = holdSerializer(items)
        return Response(serializer.data)

Serializer.py

class holdSerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemBatch
        fields = "__all__"

But when I run this it says :

ValueError at /api/dispatchhistoryitem/43/

dictionary update sequence element #0 has length 1; 2 is required

What is that I am doing wrong here ? Please Help!

Upvotes: 3

Views: 10988

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

I think essentially the problem is that you use the wrong view. A ListAPIView is used to retrieve, well, a list of objects.

You can here use a RetrieveAPIView [drf-doc] which already implements the boilerplate logic. If your URL contains a pk parameter, it can automatically filter on that pk, so there is no need to implement this logic yourself:

from rest_framework.generics import RetrieveAPIView

class dispatchhistoryitemsview(RetrieveAPIView):
    queryset = ItemBatch.objects.all()
    serializer_class = holdSerializer

Furthermore, as @ruddra says you should use a named parameter, since the third parameter is the kwargs:

path(
    'api/dispatchhistoryitem/<int:pk>/',
    views.dispatchhistoryitemsview.as_view(),
    name='dispatchhistoryitem'
),

Upvotes: 6

Related Questions