How to return primary key as a response when ever we make a post request using django rest framework?
我有django模型,它的视图定义为:
1 2 3 4 | class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer |
我该怎么做才能将主键作为响应返回?
这是我的Json在发布请求后的样子:
1 2 3 4 5 6 7 | { "id": 4, "UID":"465666700", "name":"rohit", "gender":"MALE", "yob":"1996" } |
我的回答应该是:4即主键
`class ItemSerializer(serializers.ModelSerializer):
1 2 3 | class Meta: model = Item fields = ('id', 'name', 'mrp','imageid', 'company', 'edible','discount','seller_uid','seller_pk')` |
帮助感谢。
为Item模型声明ModelSerializer。 将fields属性设置为['id'],这应该有效!
1 2 3 | class ItemSerializer(serializers.ModelSerializer): model = Item fields = ['id'] |
只需在
1 2 3 4 | from rest_framework import serializers class ItemSerializer(serializers.Serializer): id = serializers.IntegerField(source='pk') |