foreignKey模型没有Manager(即“Foo”对象没有属性“foo_set”)
我四处寻找这个问题的答案,但找不到。使用外键时,我不断收到错误消息,告诉我“Foo 对象没有属性“foo_set”。我对 Django/Python 有点陌生,所以我确信这里有一个简单的答案,但到目前为止我还没有找到它。下面是一些代码(用于存储游戏中使用的各种棋盘,每个棋盘都应该有多个与之关联的六角形):
模型:
class Boards(models.Model):
boardnum = models.IntegerField(unique=True)
boardsize = models.IntegerField(default=11)
hexside = models.IntegerField(default=25)
datecreated = models.DateTimeField(auto_now_add = True)
class Hexes(models.Model):
boardnum = models.ForeignKey(Boards, null = True)
col = models.IntegerField()
row = models.IntegerField()
cost = models.IntegerField(default=1)
代码(有效):
newboard, createb = Boards.objects.get_or_create(boardnum=boardn)
createb 返回 True。
代码(这立即遵循上述内容,并且不起作用):
try:
hx = newboard.boards_set.create(col=c, row=r)
except Exception, err:
print "error:", err
traceback.print_exc()
“err”和“traceback.print_exc()”都给出: AttributeError: 'Boards' object has no attribute 'boards_set'
我得到如果我首先使用 get_or_create 创建 Hexes 记录,然后在其上尝试 newboard.boards_set.add() ,则会出现同样的错误。
有什么想法吗?所有建议均表示赞赏。
I have searched around for an answer to this but can't find one. When using a ForeignKey, I am consistently getting an error telling me that 'Foo object has no attribute 'foo_set'. I am a bit new to Django/Python, so I'm sure there is a simple answer here, but I haven't been able to find it so far. Here's some code (to store varied Boards for use in a game, each of which should have a number of Hexes associated with it):
Models:
class Boards(models.Model):
boardnum = models.IntegerField(unique=True)
boardsize = models.IntegerField(default=11)
hexside = models.IntegerField(default=25)
datecreated = models.DateTimeField(auto_now_add = True)
class Hexes(models.Model):
boardnum = models.ForeignKey(Boards, null = True)
col = models.IntegerField()
row = models.IntegerField()
cost = models.IntegerField(default=1)
Code (this works):
newboard, createb = Boards.objects.get_or_create(boardnum=boardn)
createb returns True.
Code (this immediately follows the above, and does not work):
try:
hx = newboard.boards_set.create(col=c, row=r)
except Exception, err:
print "error:", err
traceback.print_exc()
Both "err" and "traceback.print_exc()" give: AttributeError: 'Boards' object has no attribute 'boards_set'
I get the same error if I first create the Hexes record with a get_or_create and then try a newboard.boards_set.add() on it.
Any ideas? All suggestions appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Django 用于反向外键管理器的名称是包含外键的模型的名称,而不是管理器所在模型的名称。
在您的情况下,它将是:
我发现使用
manage.py shell
命令导入模型并检查它们(使用dir
等)来检查非常有用所有可用的属性。The name that Django uses for a reverse foreign key manager is the name of the model that contains the foreign key, not the name of the model that the manager is on.
In your case, it will be:
I find it useful to use the
manage.py shell
command to import your models and inspect them (withdir
, etc) to check out all the available attributes.