在django rest framework中通过post-request创建后返回一个字段

n3schb8v  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(97)

这是我基于类的观点:

class PurchaseAPICreate(generics.CreateAPIView):
    serializer_class = PurchaseSerializer

和串行器:

class PurchaseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Purchase
        fields = "__all__"

Get-request返回我所有字段,但我只需要id。我尝试了fields = ('id',)。但post请求需要所有字段进行序列化。我这样做了,但认为它不应该以这种方式工作。

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']
        })

我怎样才能得到唯一的身份证呢?

djmepvbi

djmepvbi1#

你可以在序列化器的 meta类的extra_kwargs中设置只读或写。

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}
        }

相关问题