问题描述
如果 product
有 base_image=True
,我试图阻止某个插入,但在 base_image=False
时允许任意数量的插入。
我已经用 django.db.models.UniqueConstraint
实现了它,一切正常,但是在 django 管理面板中,我没有在添加视图时收到红色警报,而是收到了 IntegrityError
。
这是我的模型 (media.py
):
from django.db import models
from apiv1.models.products import Product
class Media(models.Model):
""" Media table,contains images file names """
product = models.ForeignKey(Product,related_name='media',on_delete=models.CASCADE,blank=False)
file_name = models.CharField(max_length=191,blank=False,unique=True)
base_image = models.BooleanField(blank=False)
class Meta:
constraints = [
models.UniqueConstraint(
fields=[
'product',],condition=models.Q(base_image=True),name='unique_base_image'
),]
def __str__(self):
return self.file_name
这是错误:
IntegrityError at /admin/apiv1/media/add/
UNIQUE constraint Failed: apiv1_media.product_id
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/apiv1/media/add/
Django Version: 3.1.4
Exception Type: IntegrityError
Exception Value:
UNIQUE constraint Failed: apiv1_media.product_id
Exception Location: /Users/sal/devel/artiashco_tipnety_cbir/env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py,line 413,in execute
Python Executable: /Users/sal/devel/artiashco_tipnety_cbir/env/bin/python
Python Version: 3.7.3
Python Path:
['/Users/sal/devel/artiashco_tipnety_cbir','/Library/Developer/CommandLinetools/Library/Frameworks/python3.framework/Versions/3.7/lib/python37.zip','/Library/Developer/CommandLinetools/Library/Frameworks/python3.framework/Versions/3.7/lib/python3.7','/Library/Developer/CommandLinetools/Library/Frameworks/python3.framework/Versions/3.7/lib/python3.7/lib-dynload','/Users/sal/devel/artiashco_tipnety_cbir/env/lib/python3.7/site-packages']
Server time: Wed,30 Dec 2020 12:58:16 +0000
期望:django 管理面板中的红色引导程序警报
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)