对以下对象使用POST方法后,我想以JSON格式返回创建对象的id。我尝试将python字典转换为json格式,但没有工作。
{
"name": "m15",
"url": "https://i.pinimg.com/originals/6f/fb/bd/6ffbbd3938131ddd7f07948966772435.jpg",
"caption": "c15"
}
预期输出
{
'id':15
}
以下是我的观点。py
from rest_framework import generics
from .models import Meme
from .serializers import MemeSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class ListMeme(APIView):
"""
List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
memes = Meme.objects.all()
serializer = MemeSerializer(memes, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = MemeSerializer(data=request.data)
print(request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class DetailMeme(generics.RetrieveUpdateDestroyAPIView):
queryset = Meme.objects.all()
serializer_class = MemeSerializer
在上述情况下,一个简单的方法是重写MemeSerializer
的create方法。
在MemeSerializer
的创建方法
def create(self, validated_data):
"""
Overriding the create method to return
only id of created instance
"""
meme: Meme = Meme.objects.create(**validaed_data)
return {id: meme.id}
解决此问题的另一种方法是创建另一个模型序列化器,将所有其他字段作为read_only
,而id
仅作为write_only
字段。反过来,这可以通过两种不同的方式来完成
# method 1
class CreateMemeSerializer(serializers.ModelSerializer):
name: str = serializers.CharField(max_length=..., read_only)
...
id: int = serializers.IntegerField(write_only=True)
class Meta:
model = Meme
# method 2
class CreateMemeSerializer(serializers.ModelSerializer):
class Meta:
model = Meme
...
extra_kwags = {
"name": {"read_only": True},
...
"id": {"write_only": True},
}
# and use this in your view
...
def post(self, request, format=None):
serializer = CreateMemeSerializer(data=request.data)
...
另外,你也可以在你的情况下使用视图集。