Skip to content
Advertisement

SQLAlchemy nested model creation one-liner

I’m looking to create a new object from q2, which fails because the Question class is expecting options to be a dictionary of Options, and it’s receiving a dict of dicts instead.

So, unpacking obviously fails with a nested model.

What is the best approach to handle this? Is there something that’s equivalent to the elegance of the **dict for a nested model?

main.py

JavaScript

base.py

JavaScript

question.py

JavaScript

option.py

JavaScript

Advertisement

Answer

I liked the answer provided by @Abdou, but wanted to see if I couldn’t make it a bit more generic.

I ended up coming up with the following, which should handle any nested model.

JavaScript

Listens for the init event of any specified models, checks for relationships that match the kwargs passed in, and then converts those to the matching class of the relationship.

If anyone knows how to set this up so it can work on all models instead of specifying them, I would appreciate it.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement