简体   繁体   中英

FOREIGN KEY constraint failed - Django

So I'm trying to make a delete route for my API but I'm encountering a problem. Whenever I hit the delete route I get an error which is django.db.utils.IntegrityError: FOREIGN KEY constraint failed . I'm trying to delete a model if the delete route is hit. I have done makemigrations and migrate but there were no changes. Example of my code is like this:

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

product in 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

You should be using django-rest-framework's serializers and viewsets to achieve this. ( RTFM )


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

Reference to DRF's docs.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM