首页 > 解决方案 > 使用 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!

根据文档,我尝试UniqueConstraintMeta类中添加 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错误的正确方法吗?约束是否应该在非托管模型上起作用?

标签: djangodjango-models

解决方案


我认为如果对象是非托管的,在 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

看一下MultipleObjectsReturned异常的参考


推荐阅读