Array Definition Modelling in MongoAlchemy

喜你入骨 提交于 2020-01-13 06:38:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!