mongodb的嵌入式文档可以在web2py DAL中建模吗?

时间:2014-02-10 10:00:35

标签: mongodb web2py database

如何在Web2PY DAL中建模这个mongodb嵌入式文档结构?

{
   _id: "joe",
   name: "Joe Bookreader",
   addresses: [
                {
                  street: "123 Fake Street",
                  city: "Faketon",
                  state: "MA",
                  zip: 12345
                },
                {
                  street: "1 Some Other Street",
                  city: "Boston",
                  state: "MA",
                  zip: 12345
                }
              ]
 }

2 个答案:

答案 0 :(得分:1)

在此处的文档部分中查找list和'json`类型:

http://www.web2py.com/book/default/chapter/06#Record-representation

答案 1 :(得分:1)

对于mongodb,web2py DAL可以是这样的

db = DAL('mongodb://username:password@localhost/test', pool_size=0)
db.define_table('address',
                Field('street'),
                Field('city'),
                Field('state'),
                Field('zip'),
                format='%(name)s')

db.define_table('table',
                Field('name'),
                Field('address','list:reference address'),
                format='%(name)s')

要插入,您可以

first = db.address.insert(street = '123 Fake Street',
                          city = 'Faketon',
                          state = 'MA',
                          zip = '12345')
second = db.address.insert(street = '1 Some Other Street',
                          city = 'Boston',
                          state = 'MA',
                          zip = '12345')
db.table.insert(name = 'Joe Bookreader', address = [first, second])

或直接您可以执行以下代码:

db.define_table('table_name',Field('name'),Field('addresses','text'))
list_data =  [
            {
              street: "123 Fake Street",
              city: "Faketon",
              state: "MA",
              zip: 12345
            },
            {
              street: "1 Some Other Street",
              city: "Boston",
              state: "MA",
              zip: 12345
            }
          ]
db.table_name.insert(name='Joe Bookreader', addresses=list_data)