Helping Snippets - Add attributes to your SQLAlchemy model from a dictionary

I wanted to add all attributes from a dictionary to my model, the only problem is, the dictionary has to have the exact same keys as the model. In my case the dictionary has more keys, so I ran into errors when using MyModel(**dict).

This is why I created a small function I placed inside my model class, to handle that problem for me:

class MyModel:
    def add_attributes_from_dict(self, attribute_list: dict) -> None:
        model_attribute_list = self.__mapper__.attrs.keys()

        for key, value in attribute_list.items():

            if key in model_attribute_list:
                setattr(self, key, value)

This will only add the attributes if they are present inside the model.

If you know a better way to solve this, let me know on Twitter

Subscribe to Eduard Schwarzkopf

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.