[英]FOREIGN KEY constraint failed - Django
所以我試圖為我的 API 創建一條刪除路線,但我遇到了一個問題。 每當我點擊刪除路線時,我都會收到一個錯誤django.db.utils.IntegrityError: FOREIGN KEY constraint failed
。 如果刪除路線被擊中,我正在嘗試刪除 model 。 我已經完成了makemigrations
和migrate
但沒有任何變化。 我的代碼示例如下:
class RandomAPIView(APIView):
def delete(self, request, id, format=None):
product = Product.objects.get(pk=id)
product.delete()
return Response({'Success':'Product has been deleted'})
models.py 中的產品
class Product(models.Model):
name = models.CharField(max_length=200)
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.name
您應該使用 django-rest-framework 的序列化程序和視圖集來實現這一點。 (實時調頻)
## serializers.py
from rest_framework import serializers
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = "__all__"
## views.py
from rest_framework import viewsets, mixins
# below subclassing is done to only allow deletion,
# u can also use `viewsets.ModelViewSet` to allow all operations
# such as `list`, `create`, etc.
class ProductViewSet(viewsets.GenericAPIView, mixins.DestroyModelMixin):
queryset = Product.objects.all()
serializer_class = ProductSerializer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.