【问题标题】:How to append field to already defined table in web2py?如何将字段附加到 web2py 中已定义的表?
【发布时间】:2013-10-01 04:09:49
【问题描述】:

给定一个我通过db.define_table('xyz'..) 定义的表 xyz,我可以将其引用为 db.xzy,我如何向这个已经定义的表对象添加一个新字段?

我正在考虑的用例是我想将created 字段添加到多个表中。我也想避免重复自己。我的想法是创建一个函数,该函数接受一个表并将created 字段添加到其中。比如:

def addcreated(table):
    # ??? somehow add a new Field('created', 'datetime') to table
    table.created.writable = False
    table._before_insert.append...
    ... etc.

db.define_table('product',
    Field('name','string'),
    Field('weight','double')
)

db.define_table('customer',
    Field('name','string'),
    Field('address','string')
)

addcreated(db.product)
addcreated(db.customer)

【问题讨论】:

    标签: web2py auditing datecreated


    【解决方案1】:
    created_field = Field('created', 'datetime', writable=False)
    
    db.define_table('product',
        Field('name','string'),
        Field('weight','double'),
        created_field)
    

    或:

    db.define_table('product',
        Field('name','string'),
        Field('weight','double'),
        created_field.clone(...))
    

    使用.clone(),您可以获得Field 对象的副本,并且可以指定一组新参数来更改其某些属性。

    要重复使用多个字段,请参阅table inheritance 上的文档。

    【讨论】:

    • clone() 是否也适用于 Table 对象或仅适用于单个字段?
    • .clone() 是Field 类的方法。 Table 类没有类似的东西。
    • 您也可以使用*args 定义字段。您可以创建Field 对象列表并执行以下操作:db.define_table('product', *fields)。
    【解决方案2】:

    也许你应该考虑使用 db._common_fields.append (http://web2py.com/books/default/chapter/29/06/the-database-abstraction-layer?#Common-fields-and-multi-tenancy)

    例如,如果您想获取记录的创建日期,您可以在表格定义之前添加以下行:

    signature = db.Table(db,'auth_signature',
          Field('created_on','datetime',default=request.now,
                writable=False,readable=False, label=T('Created on')),
            Field('created_by','reference %s' % auth.settings.table_user_name,default=auth.user_id,
                writable=False,readable=False, label=T('Created by'))
          )
    
    db._common_fields.append(signature) #db._common_fields is a list of fields that should belong to all the tables
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      • 2011-06-08
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      • 2023-04-11
      • 2010-11-09
      相关资源
      最近更新 更多