1

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)
styvane
  • 59,869
  • 19
  • 150
  • 156
mathema
  • 939
  • 11
  • 22
  • Author here. If address is a list you want ListField(DocumentField(Address)). You're getting the "items" error because MA is trying to parse that as a document field, which should be a dict. – Jeff Jenkins Jul 15 '16 at 12:29

2 Answers2

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)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • @mathema updated the answer with some more information. You can also put document fields into list fields if needed, sample [here](https://github.com/jeffjenkins/MongoAlchemy/blob/master/examples/advanced_modeling.py#L14). Hope that helps. – alecxe Jul 14 '16 at 15:17
  • Yes, I have already tried this solution but I took error like "AttributeError AttributeError: 'list' object has no attribute 'items' ". – mathema Jul 14 '16 at 15:20
0

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())
simanacci
  • 2,197
  • 3
  • 26
  • 35