0

I am trying to insert data in a nested format.

A snippet of my models (there are many, many more):

class LifetimeMode(db.EmbeddedDocument):
    meta = {'collection': 'lifetime_mode'}
    career = db.EmbeddedDocumentField(GameModeData)
    war = db.EmbeddedDocumentField(GameModeData)
    sd = db.EmbeddedDocumentField(GameModeData)
    dom = db.EmbeddedDocumentField(GameModeData)

class LifetimeData(db.EmbeddedDocument):
    meta = {'collection': 'lifetime_data'}
    mode = db.EmbeddedDocumentField(LifetimeMode)

class UserData(db.EmbeddedDocument):
    meta = {'collection': 'user_data'}
    timestamp = db.DateTimeField(default=datetime.utcnow)
    type = db.StringField()
    level = db.IntField()
    lifetime = db.EmbeddedDocumentField(LifetimeData)

class User(db.Document):
    meta = {'collection': 'user'}
    public_id = db.UUIDField()
    gamer_id = db.StringField()
    user_data = db.EmbeddedDocumentField(UserData)

When I try to create my database with dummy data I am running into an issue I cannot solve. I grab my data from an external API.

lt_mode_data = data['lifetime']['mode'] # << This is the API returned data
for mode, mode_data in lt_mode_data.items():
    game_mode_data = GameModeData()
    lifetime_mode = LifetimeMode()
    json_data = json.dumps(mode_data['properties'])
    lifetime_mode[mode] = game_mode_data.from_json(json_data)

The problem is that only the final mode is added, as if each modes data gets added but is then overwritten by the next.

Any ideas?

1

To solve this problem I changed the code to the following:

lt_mode_data = data['lifetime']['mode']
    mode_dict = {}
    game_mode_data = GameModeData()
    lifetime_mode = LifetimeMode()
    for index, (mode, mode_data) in enumerate(lt_mode_data.items()):
        mode_dict[mode] = mode_data['properties']
    lifetime_mode = lifetime_mode.from_json(game_mode_data.from_json(json.dumps(mode_dict)).to_json())
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.