Referencing a table in web2py before defining it

白昼怎懂夜的黑 提交于 2019-12-08 11:45:11

问题


My code is the following im trying to assign a department to employees and also create a manager in a department table

db = DAL(lazy_tables=True)
db.define_table('employee',
            Field('fullname','string',label='Name'),
            Field('email','string'),
            Field('phone','string'),
            Field('kids', 'string'),
            Field('phone', 'string'),
            #Field('date','datetime'),
            Field('dob', 'datetime', label='Date'),
            Field('department', 'reference department',
                  requires=IS_IN_DB(db, db.department.id, '%(department_name)s')),
            auth.signature,
            format='%(fullname)s'

            )
db = DAL(lazy_tables=True)
db.define_table('department',
            Field('department_name', 'string', label='Department Name'),
            # Field('department_name', 'string', label='Department Name'),
            Field('manager', 'reference employee', required='true',
                  requires=IS_IN_DB(db, db.employee.id, '%(fullname)s')),
            auth.signature,
            format='%(department_name)s'
            )

回答1:


If you remove the 2nd db = DAL(lazy_tables=True), you should be fine.

The problem you have is that you essentially overwrote the first db object by declaring/instantiating it again after the first table definition (employee).

This gives you a new db object (with no tables defined) in which you define a table (department) that references another table (employee) that no longer exists.




回答2:


    Field('department', 'reference department',
          requires=IS_IN_DB(db, db.department.id, '%(department_name)s')),

In the above line, you reference db.department.id, but the department table has not yet been defined, so the db object will not yet have a department attribute.

You should instead be able to use this alternative syntax:

IS_IN_DB(db, 'department.id', '%(department_name)s')

Alternatively, you can define the requires attribute after defining the department table:

db.employee.department.requires = IS_IN_DB(db, db.department.id, '%(department_name)s')


来源:https://stackoverflow.com/questions/38946510/referencing-a-table-in-web2py-before-defining-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!