This is my class-based view:
class PurchaseAPICreate(generics.CreateAPIView):
serializer_class = PurchaseSerializer
and serializer:
class PurchaseSerializer(serializers.ModelSerializer):
class Meta:
model = Purchase
fields = "__all__"
Get-request return me all fields, but I need only id
. I tried fields = ('id',)
. But post request needs all fields for serialization. I did this, but think it shouldn't work in this way.
class PurchaseAPICreate(generics.CreateAPIView):
serializer_class = PurchaseSerializer
queryset = Shop.objects.all()
def create(self, request, *args, **kwargs):
queryset = self.get_queryset()
serializer = PurchaseSerializer(queryset, many=True)
return Response({
'id': serializer.data[len(serializer.data)-1]['id']
})
How I can get only id in right way?
You can set write or read only in extra_kwargs in the Meta class of a serializer. Eg
class PurchaseSerializer(serializers.ModelSerializer):
class Meta:
model = Purchase
fields = "__all__"
extra_kwargs = {
'field_1': {'write_only': True},
'field...N': {'write_only': True},
'id': {'read_only': True}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.