MhmdRizk
MhmdRizk

Reputation: 1721

Adding the primary key to the serializer

I want to add the id field, which is the primary key to each object, in the list I'm returning

in my models.py:

class Category(models.Model):
     name = models.CharField(max_length=200)

in my serializers.py:

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

in my views.py:

class ListCategoriesView(generics.ListAPIView):
"""
Provides a get method handler.
"""

serializer_class = CategorySerializer


def get(self, request, *args, **kwargs):
    token = request.META.get("HTTP_TOKEN","")
    if not token:

        """ do some action here """

    if not UserAccess.objects.filter(accessToken=token).exists():

        """ do some action here """

    else:
        serialized_categories = []
        all_categories = Category.objects.all()
        for category in all_categories:
          """ I'm filling the object here with the id , and the name """
            serialized_item = CategorySerializer(data={
                    "id": category.id,
                    "name": category.name
                })
            if serialized_item.is_valid():
                serialized_categories.append(serialized_item.data)
        return Response(
            data=serialized_categories,
            status=status.HTTP_200_OK
        )

I'm getting the below reponse :

enter image description here

I want to get this response just with the id field added:

enter image description here

Upvotes: 0

Views: 1417

Answers (1)

lostbard
lostbard

Reputation: 5230

Just allow the view to do the work.

class ListCategoriesView(generics.ListAPIView):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()

    def list(self, request, *args, **kwargs)
        token = request.META.get("HTTP_TOKEN","")
        if not token:
            """ do some action here """
        elif not UserAccess.objects.filter(accessToken=token).exists():
            """ do some action here """
        else:
            return super().list(request, *args, **kwargs)

Upvotes: 2

Related Questions