在Django管理员中使用UniqueConstraint解决“ get()返回多个错误”的错误

时间:2019-04-16 14:43:12

标签: django django-models

我正在尝试通过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个!

根据documentation,我尝试在UniqueConstraint类中添加Meta,但约束似乎没有任何作用,并且上述错误仍然存​​在:

    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错误的正确方法吗?约束即使在非托管模型上也应该起作用吗?

2 个答案:

答案 0 :(得分:1)

我认为如果对象不受管理,则在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 exception的引用

答案 1 :(得分:0)

Another approach is to add .first() to your get(). That guarantees you will get a single result (or None), and will avoid errors at that point.

If the duplicates are a problem it sounds like you need to investigate how they are being created, fix that and then do some clear up.