django - 使用 UniqueConstraint 解决 Django admin 中的“get() 返回多个”错误
问题描述
我正在尝试通过 Django 管理仪表板访问(非托管)模型。该模型没有主键,而是在三个字段中是唯一的。
class MyObjectView(models.Model):
solution_id = models.IntegerField(blank=True, null=True)
scenario_id = models.IntegerField(blank=True, null=True)
object_id = models.CharField(max_length=256, blank=True, null=True)
description= models.CharField(max_length=1000, blank=True, null=True)
year_of_creation = models.DateField(blank=True, null=True)
class Meta:
managed = False # Created from a view. Don't remove.
db_table = 'myobject_view'
虽然我能够访问管理仪表板中所有项目的列表,但当我尝试查看一个特定项目时,我会收到错误消息:
get() 返回了多个 MyObjectView —— 它返回了 4!
根据文档,我尝试UniqueConstraint
在Meta
类中添加 a ,但约束似乎没有任何效果,并且上面的错误仍然存在:
class Meta:
managed = False # Created from a view. Don't remove.
db_table = 'myobject_view'
constraints = [
models.UniqueConstraint(fields=['solution_id', 'scenario_id', 'object_id '], name='unique_object'),
]
这是解决get() returned more than one
错误的正确方法吗?约束是否应该在非托管模型上起作用?
解决方案
我认为如果对象是非托管的,在 Meta 中添加 UniqueConstraint 不会在数据库中插入任何约束。
您需要捕获异常:
try:
the_object = MyObjectView.objects.get(
object_id=object_id, scenario_id=scenario_id, solution_id=solution_id
)
return the_object # or do something different
except MyObjectView.MultipleObjectsReturned:
# multiple objects have the three same values
# manage that case
return None # just as example
推荐阅读
- docker - 根据 dns 地址访问不同 docker 容器上的不同网站
- cmake - 如何让 CMake 自动检测 CUDA_ARCHITECTURES 的值?
- java - 如何在 JPA 中将对象转换为实体
- android - android native crash by lib64/libhwui.so ,以及如何定位问题
- r - 匹配R中两个数据帧的模糊字符串
- sql-server - 在插入 sql 触发器时将 SQL Server 数据发送到 PostgreSQL
- javascript - 如何使用从 api 获取的数据在 javaScript 中创建选择下拉列表
- r - 未正确将节点度设置为节点属性 -R
- azure-active-directory - 身份验证在本地主机上工作,不适用于生产
- unicode - 在 VB6 应用程序中如何处理 DLL 错误消息的编码/本地化?