OneToOne Field django

时间:2013-11-05 12:22:13

标签: django one-to-one

我有以下型号

class Entry(models.Model):
    #fields....


class EntryHistory(models.Model):
     entry = models.OneToOneField(Entry, related_name='history')
     text =.....etc

但是当我尝试访问entry.history时,我得到了一个DoesNotExist异常

shell中的代码

entry = Entry.objects.get(pk = 4)
entry_history = entry.history
    raise self.related.model.DoesNotExist
DoesNotExist

我想检查是否为特定条目添加了entry_history。所以我想获得entry.history并检查

if entry_history:

查看是否有entry_history。 DoesNotExist是什么意思?

 hasattr(entry, 'history')

也会返回false。

编辑: SQL表创建代码

CREATE TABLE "mycal_entryhistory" ("id" integer NOT NULL PRIMARY KEY, "entry_id" integer NOT NULL UNIQUE, "text" text NULL, "doctor_id" integer NOT NULL)

这是否意味着我的桌子没有正确创建?

1 个答案:

答案 0 :(得分:2)

您想要检查是否为特定条目添加了entry_history,而related.model.DoesNotExist表示它不存在,因此异常是您问题的答案。

entry = Entry.objects.get(pk=4)
try:
    entry_history = entry.history
    # if this code runs it means the object exists
except entry.history.model.DoesNotExist:
    # it does not exist

或者你可以使用count:

entry = Entry.objects.get(pk=4)
if entry.history.count():
    # it does exist