1

My model class for user collection looks like this.

class User(UserMixin,db.Document):
    config_extra_fields = 'ignore'
    first_name = StringField()
    last_name = StringField()
    def get_id(self):
        return str(self.mongo_id)

To insert value to this collection I use the following code:

user = User(first_name="FN", last_name="LN", finale_name="SOMENAME")
user.save()

I tried setattr, But it is ignoring the attributes that are not defined in the class.

Its working fine and even the finale_name is added to the document. However, I am unable to insert it dynamically.

Can I insert a dictionary to mongo using that class? Something like this?

user = User({
        "first_name": "NEW NAME",
        "last_name": "LAST NAME",
        "username": "USER NAME",
        "one_more": "Hello"
    })
Codeformer
  • 2,060
  • 9
  • 28
  • 46

1 Answers1

0

Use below code:

data = {
        "first_name": "NEW NAME",
        "last_name": "LAST NAME",
        "username": "USER NAME",
        "one_more": "Hello"
       }

user = User(**data)
Ajay saini
  • 2,352
  • 1
  • 11
  • 25