MongoAlchemy中的数组定义建模

时间:2016-07-14 15:06:43

标签: python mongodb flask mongoalchemy

我尝试在Flask中模拟我的MongoAlchemy类。这是我的模特:

{
    "_id" : ObjectId("adfafdasfafag24t24t"),
    "name" : "sth."
    "surname" : "sth."
    "address" : [
     {
      "city" : "Dublin"
      "country" : "Ireland" 
   }
  ]
}

这是我的documents.py类:

   class Language_School(db.Document):
        name = db.StringField()
        surname = db.StringField()
        address = db.???

如何在Flask中定义类似数组模型(地址)?

修改:在问问题之前,我已经尝试过我的模型。但我接受了像#34; AttributeError这样的错误 AttributeError:' list'对象没有属性''"。

class Address(db.Document):
    city = db.StringField()
    country = db.StringField()

class Language_School(db.Document):
    name = db.StringField()
    surname = db.StringField()
    address = db.DocumentField(Address)

2 个答案:

答案 0 :(得分:1)

您从我的理解中询问ListField

但是,我不确定您确实需要一个列表来存储地址,为什么不使用特殊文档类型 - DocumentField,遵循示例here

class Address(Document):
    street_address = StringField()
    city = StringField()
    state_province = StringField()
    country = StringField()

class User(Document):
    name_index = Index().ascending('name').unique()
    name = StringField()
    email = StringField()

    address = DocumentField(Address)

    def __str__(self):
        return '%s (%s)' % (self.name, self.email)

答案 1 :(得分:0)

您可以使用ListField并将该城市作为列表中的第1项和国家/地区作为列表中的第2项。

{
    "_id" : ObjectId("adfafdasfafag24t24t"),
    "name" : "sth."
    "surname" : "sth."
    "address" : ["Dublin", "Ireland"]
}

class Language_School(db.Document):
    name = db.StringField()
    surname = db.StringField()
    address = db.ListField(db.StringField())