FOREIGN KEY constraint failed (IntegrityError) while adding a value to a ManyToManyField in Django

Exception Type: IntegrityError Exception Value:FOREIGN KEY constraint failed Exception Location: django/db/backends/base/base.py, line 303, in _commit Raised during: django.contrib.admin.options.change_view

Here is my model class

class ReviewModel(models.Model):
    title=models.CharField(max_length=100)
    description=models.CharField(max_length=200)
    reviewer=models.ForeignKey(UserModel,on_delete=models.SET_NULL,null=True,blank=True)

class ProductsModel(models.Model):
    uid=models.CharField(max_length=100,primary_key=True)
    name=models.CharField(max_length=100)
    description=models.CharField(max_length=200)
    category=models.ForeignKey(ProductCategoryModel,on_delete=models.CASCADE) 
    price=models.PositiveIntegerField()
    image1=models.ImageField(upload_to="images/products")
    seller=models.ForeignKey(UserModel,on_delete=models.CASCADE)
    reviews=models.ManyToManyField(ReviewModel,blank=False)

Here is my serializer

class ReviewSerializer(serializers.ModelSerializer):
    class Meta:
        model=ReviewModel
        fields='__all__'


class ProductsSerializer(serializers.ModelSerializer):
    reviews = ReviewSerializer(many=True, read_only=True)
    class Meta:

        model = ProductsModel
        fields='__all__'
        depth=1

Here is my views

class ProductsListView(generics.ListCreateAPIView):
    queryset=ProductsModel.objects.all()
    serializer_class=ProductsSerializer

I am able to add value and save with all fields except reviews through admin panel. When I keep it blank everything goes well but on selecting any value for reviews it raise this error.

I added create function in serializer but no change

class ProductsSerializer(serializers.ModelSerializer):
    reviews = ReviewSerializer(many=True, read_only=True)
    class Meta:

        model = ProductsModel
        fields='__all__'

    def create(self, validated_data):
        reviews_data = validated_data.pop('reviews', [])  # Handle reviews separately
        product = ProductsModel.objects.create(**validated_data)

        # If you're also creating reviews when creating a product
        for review_data in reviews_data:
            review = ReviewModel.objects.create(**review_data)
            product.reviews.add(review)

        return product 

The error was solved when I deleted the database(db.sqllite3)file and migrations folder and migrated again

Back to Top