IntegrityError:对表“ products_product”进行更新或删除违反了外键约束

时间:2020-07-04 14:04:56

标签: django postgresql django-models

我正试图从Django管理员中删除存储在PostgresSQL数据库中的所有产品,但遇到一种产品的错误消息:

IntegrityError at /admin/products/product/
update or delete on table "products_product" violates foreign key constraint "products_curateprodu_product_id_ec2cf1ec_fk_products_" on table "products_curateproducts_products"
DETAIL:  Key (id)=(72) is still referenced from table "products_curateproducts_products".

在Django admin中的Curranted Products下,我没有任何产品,我无法弄清楚为什么会显示该错误。至少它不会显示任何内容,只有0个策展产品。

此处是产品型号的代码:

class Product(models.Model):
    seller = models.ForeignKey(SellerAccount, on_delete=models.CASCADE)
    media = models.ImageField(blank=True,
            null=True,
            upload_to=download_media_location,
            storage=FileSystemStorage(location=settings.PROTECTED_ROOT))
    title = models.CharField(max_length=150)
    slug = models.SlugField(blank=True,  unique=True)
    description = models.TextField(max_length=200, null=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=9.99, null=True)
    sale_active =models.BooleanField(default=False)
    sale_price = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Product'
        verbose_name_plural = 'Products'
        ordering = ['title']

和“策展产品”模型的代码:

class CuratedProducts(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
    section_name = models.CharField(max_length=20, null=True, blank=True)
    products = models.ManyToManyField(Product, blank=True)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.section_name

    class Meta:
        verbose_name = 'Curated Product'
        verbose_name_plural = 'Curated Products'

更新,使用:

Django 3.0.5, psycopg2-binary 2.8.5

1 个答案:

答案 0 :(得分:0)

错误消息显示:

DETAIL:  Key (id)=(72) is still referenced from table "products_curateproducts_products".

记下名称curateproducts_products。确实与您显示的模型匹配。组合中还有另一个表。