DJANGO - RelatedObjectDoesNotExist

时间:2015-01-21 19:39:40

标签: python django django-models

我对经典遗产有疑问:

我的模特:

class Scribe(models.Model):
    user = models.OneToOneField(User)

    def __str__(self):
        return "{ "+self.user.username+" } "

class membre(Scribe): 
    def __str__(self):
        return "{ pseudo :"+self.user.username+" } "

在shell中我这样做:

  • U = User.objects.create_user(用户名= “拉拉”)
  • S =抄写(U)
  • M = membre(S)

但是当我在shell中执行此操作时:m或m.user.username我有这个错误:

RelatedObjectDoesNotExist:Scribe没有用户

1 个答案:

答案 0 :(得分:0)

Scribe作为外键添加到membre

class Scribe(models.Model):
    user = models.OneToOneField(User)
    def __str__(self):
        return "{ " + self.user.username + " } "

class membre(models.Model):
    scribe = models.ForeignKey(Scribe)
    def __str__(self):
        return "{ pseudo :" + self.scribe.user.username + " } "

然后您可以使用create方法实例化两个模型:

u = User.objects.create_user(username="lala")
s = Scribe.objects.create(user=u)
m = membre.objects.create(scribe=s)

print s
print m