在 Django 中向 ManyToManyField 添加值时,FOREIGN KEY 约束失败 (IntegrityError)

问题描述 投票:0回答:1

异常类型:IntegrityError 异常值:FOREIGN KEY 约束失败 异常位置:django/db/backends/base/base.py,第303行,在_commit中 期间引发:django.contrib.admin.options.change_view

这是我的模型课

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)

这是我的序列化器

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

这是我的看法

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

我可以通过管理面板添加除评论之外的所有字段的价值并保存。 当我将其保留为空白时,一切都会顺利,但在选择任何评论值时,会引发此错误。

我在序列化器中添加了创建函数,但没有改变

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 
django django-models django-rest-framework django-views django-forms
1个回答
0
投票

当我删除数据库(db.sqllite3)文件和迁移文件夹并再次迁移时,错误解决了

© www.soinside.com 2019 - 2024. All rights reserved.