1

Im fetching a nested dataset using the following query:

users = db.query(User).options(subqueryload(User.orders))

I want to turn the result into a dict. The method I'm currently using is:

for user in users:
    user.__dict__

This approach turns the user object into a dict, but the nested dataobject (orders) is still a models.Orders object:

{'id: 1L, 'username': "some_username", "orders": [<models.Orders object at 0x10608d90>,<models.Orders object at 0x40107d90>,]}

How can I convert all nested data objects into dicts?

A generic solution is preferable.

Vingtoft
  • 13,368
  • 23
  • 86
  • 135
  • 1
    `user.__dict__['orders'].__dict__` ? – Busturdust Apr 06 '16 at 13:34
  • Your solution will work in this particular case. Do you have a generic solution, that will work in cases where there is multiple subqueries with different names? – Vingtoft Apr 06 '16 at 13:48
  • I believe the `.__dict__` call uses `object.__repr__` for the string representation. Try implementing the `Orders.__repr__()` function to return a `dict` represenetation – Busturdust Apr 06 '16 at 13:58
  • Unfortunately it does not work, I get the following error: TypeError: __repr__ returned non-string (type dict) – Vingtoft Apr 06 '16 at 16:50
  • maybe something like this would work http://stackoverflow.com/questions/23252370/overloading-dict-on-python-class – Busturdust Apr 06 '16 at 17:19
  • This is a simple form of serialization. The problem itself is not well-defined, so you need to define them. Here are some questions you should think about. What if you have attributes that are not columns (e.g. `_sa_instance_state`)? What if you have circular references (e.g. a backref on `Order` that points back to `User`)? What if you have columns that are not loaded? You need to answer all these questions before you can decide on a solution. – univerio Apr 06 '16 at 18:47
  • `_sa_instance_state` and backrefs should be ignored. I assumed that my question described a normal use case and I therefore hoped a solution already existed. – Vingtoft Apr 06 '16 at 19:49
  • I disagree that this is a "normal" use case. It might appear normal to you, but the very existence of these questions means that somebody will perceive some other set of requirements as "normal". What if my use case calls for backrefs to be represented by references to the parent `dict`? Serialization like this is difficult to define precisely because requirements wildly differ, so you end up with libraries that either try to do too much or don't do what you need. In any case, your particular requirements can be easily implemented recursively. – univerio Apr 06 '16 at 21:28
  • You are probably right @univerio . I have now implemented a recursively algorithm that works beautifully. Thanks for the input, everyone. – Vingtoft Apr 06 '16 at 21:30

0 Answers0