问题
I try to model my MongoAlchemy class in Flask. Here is my model:
{
"_id" : ObjectId("adfafdasfafag24t24t"),
"name" : "sth."
"surname" : "sth."
"address" : [
{
"city" : "Dublin"
"country" : "Ireland"
}
]
}
Here is my documents.py class:
class Language_School(db.Document):
name = db.StringField()
surname = db.StringField()
address = db.???
How can I define this like array model (address) in Flask?
Edit: I have already tried to my models like before asking question. But I took error like "AttributeError AttributeError: 'list' object has no attribute '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)
回答1:
You are asking about the ListField from what I understand.
Though, I am not sure you actually need a list to store the address, why not use the special document type - 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)
回答2:
You could use a ListField and access the city as the 1st item on the list and country as the 2nd item on the list.
{
"_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())
来源:https://stackoverflow.com/questions/38377813/array-definition-modelling-in-mongoalchemy