这是我的django模型;
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="books")
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.quantity} of {self.book.title}"
是序列化器;
class OrderItemSerializer(serializers.ModelSerializer):
book = BookSerializer(read_only=True)
class Meta:
model = OrderItem
exclude = ["user"]
这里是视图集;
class OrderItemAPIView(APIView):
serializer_class = OrderItemSerializer
permission_classes = [IsAuthenticated]
def post(self, request, pk, shipping_address_pk):
book = generics.get_object_or_404(Book, pk=pk)
order_item, created = OrderItem.objects.get_or_create(
user=request.user, book=book, ordered=False
)
shipping_address = generics.get_object_or_404(
ShippingAddress, pk=shipping_address_pk
)
order = Order.objects.create(
user=request.user, shipping_address=shipping_address
)
order.items.add(order_item)
book.stock -= 1
book.save()
order.save()
serializer_context = {"request": request}
serializer = self.serializer_class(order_item, context=serializer_context)
return Response(serializer.data, status=status.HTTP_200_OK)
如何防止非员工用户更改订购的字段或使该字段对非人员用户为只读
这是一个很好的答案,基于不同的序列化器取决于用户角色和get_serializer_class方法。
Django REST API:使字段在特定权限级别为只读