MongoAlchemy 中的数组定义建模
Array Definition Modelling in MongoAlchemy
我尝试在 Flask 中为我的 MongoAlchemy class 建模。这是我的模型:
{
"_id" : ObjectId("adfafdasfafag24t24t"),
"name" : "sth."
"surname" : "sth."
"address" : [
{
"city" : "Dublin"
"country" : "Ireland"
}
]
}
这是我的 documents.py class:
class Language_School(db.Document):
name = db.StringField()
surname = db.StringField()
address = db.???
我如何在 Flask 中定义这样的数组模型(地址)?
编辑: 在提问之前我已经试过我的模型了。但是我犯了像“AttributeError
AttributeError: 'list' 对象没有属性 'items'".
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)
据我了解,你问的是ListField
不过,我不确定您是否真的需要一个列表来存储地址,为什么不使用特殊文档类型 - DocumentField
, following the example 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)
您可以使用 ListField 并将城市作为列表中的第一项访问,将国家/地区作为列表中的第二项访问。
{
"_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())
我尝试在 Flask 中为我的 MongoAlchemy class 建模。这是我的模型:
{
"_id" : ObjectId("adfafdasfafag24t24t"),
"name" : "sth."
"surname" : "sth."
"address" : [
{
"city" : "Dublin"
"country" : "Ireland"
}
]
}
这是我的 documents.py class:
class Language_School(db.Document):
name = db.StringField()
surname = db.StringField()
address = db.???
我如何在 Flask 中定义这样的数组模型(地址)?
编辑: 在提问之前我已经试过我的模型了。但是我犯了像“AttributeError AttributeError: 'list' 对象没有属性 'items'".
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)
据我了解,你问的是ListField
不过,我不确定您是否真的需要一个列表来存储地址,为什么不使用特殊文档类型 - DocumentField
, following the example 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)
您可以使用 ListField 并将城市作为列表中的第一项访问,将国家/地区作为列表中的第二项访问。
{
"_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())