我有django模型,它的视图定义为:
from generic_relations.relations import GenericRelatedField
from rest_framework import serializers
from notes.models import Note
from leads.models import Lead
from leads.serializers import LeadSerializer
from callbacks.models import Callback
from callbacks.serializers import CallbackSerializer
class NoteSerializer(serializers.ModelSerializer):
"""
A `Note` serializer with a `GenericRelatedField` mapping all possible
models to their respective serializers.
"""
note_object = GenericRelatedField({
Lead: LeadSerializer(),
Callback: CallbackSerializer()
})
class Meta:
model = Note
fields = (
'id',
'author',
'title',
'text',
'created_date',
'note_object',
)
如何将主键作为响应返回? 这就是我的Json在发布请求后的样子:
class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
我的回答应该是:4即主键 `class ItemSerializer(serializers.ModelSerializer):
{
"id": 4,
"UID": "465666700",
"name": "rohit ",
"gender": "MALE",
"yob": "1996"
}
帮助感谢。
答案 0 :(得分:1)
为Item模型声明ModelSerializer。将字段属性设置为[' id'],这应该有效!
class ItemSerializer(serializers.ModelSerializer):
model = Item
fields = ['id']
答案 1 :(得分:0)
只需在id
中添加ItemSerializer
,例如:
from rest_framework import serializers
class ItemSerializer(serializers.Serializer):
id = serializers.IntegerField(source='pk')