开发者

ForeignKey model has no Manager (i.e., 'Foo' object has no attribute 'foo_set')

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 "trac开发者_运维问答eback.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.


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:

newboard.hexes_set.create(col=c,row=r)

I find it useful to use the manage.py shell command to import your models and inspect them (with dir, etc) to check out all the available attributes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜