0
votes

I have django model and a view for it define as:

class ItemViewSet(viewsets.ModelViewSet):

queryset = Item.objects.all()
serializer_class = ItemSerializer  

what should i do to return a primary key as response ? This is how my Json looks after making post request:

{
        "id": 4,
        "UID": "465666700",
        "name": "rohit ",
        "gender": "MALE",
        "yob": "1996"
    }

and my response should be: 4 i.e primary key `class ItemSerializer(serializers.ModelSerializer):

    class Meta:
    model = Item
    fields = ('id', 'name', 'mrp','imageid', 'company', 'edible','discount','seller_uid','seller_pk')`

Help Appreciated.

2
Could you provide a example JSON with the expected response?arcegk
@arcegk i have added the json and response i wantBhupendra Singh Chauhan
@BhupendraSinghChauhan, can you post your current ItemSerializer code in the question?Amrullah Zunzunia

2 Answers

1
votes

Just add id in your ItemSerializer, like:

from rest_framework import serializers

class ItemSerializer(serializers.Serializer):
    id = serializers.IntegerField(source='pk')
1
votes

Declare a ModelSerializer for your Item model. Set the fields attribute to ['id'] and that should work!

class ItemSerializer(serializers.ModelSerializer):
    model = Item
    fields = ['id']