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