2

I've added a new table to my Web2Py app:

db.define_table('users',
    db.Field('name', 'string'),
    db.Field('password', 'password'),
    db.Field('reputation', 'integer', default=0),
    db.Field('joined', 'datetime', default=datetime.utcnow())
)

And a field to an older table referencing it:

db.Field('user', db.users),

But this is giving me a KeyError with the following Traceback:

Traceback (most recent call last):
  File "E:\Programming\Python\web2py\gluon\restricted.py", line 204, in restricted
    exec ccode in environment
  File "E:/Programming/Python/web2py/applications/vote_up/models/db.py", line 85, in <module>
    db.Field('user', db.users),
  File "E:\Programming\Python\web2py\gluon\dal.py", line 5119, in __getattr__
    return self[key]
  File "E:\Programming\Python\web2py\gluon\dal.py", line 5113, in __getitem__
    return dict.__getitem__(self, str(key))
KeyError: 'users'

How can I fix this?

S P
  • 1,801
  • 6
  • 32
  • 55

1 Answers1

2

The "users" table has to be defined before:

db.Field('user', db.users)

Otherwise, db.users does not yet exist at the point it is referenced in the code above. Another option is:

db.Field('user', 'reference users')

which does not require the "users" table to be defined yet.

Anthony
  • 25,466
  • 3
  • 28
  • 57
  • :D How silly of me. I wasn't looking at `define_table` as a python method, but rather as some mystical Web2Py construct, like I used to look at MySQL queries during my PHP days :D . Once again, thank you @Anthony. – S P Feb 26 '12 at 14:29