Related Entities in to_dict function
See original GitHub issueI add some code for to_dict function work with related entities
@cut_traceback
def to_dict(obj, only=None, exclude=None, with_collections=False, with_lazy=False, related_objects=False, depth=1):
attrs = obj.__class__._get_attrs_(only, exclude, with_collections, with_lazy)
result = {}
for attr in attrs:
value = attr.__get__(obj)
if attr.is_collection:
if related_objects:
value = sorted(value)
elif attr.reverse.entity._pk_is_composite_:
value = sorted(item._get_raw_pkval_() for item in value)
else:
value = sorted(item._get_raw_pkval_()[0] for item in value)
elif attr.is_relation and value is not None:
if related_objects and depth - 1 >= 0:
value = value.to_dict(depth=depth - 1, with_collections=with_collections, with_lazy=with_lazy,
related_objects=related_objects)
else:
value = value._get_raw_pkval_()
if not obj._pk_is_composite_: value = value[0]
result[attr.name] = value
return result
Issue Analytics
- State:
- Created 9 years ago
- Comments:13 (5 by maintainers)
Top Results From Across the Web
python - Maintaining foreign key relations when casting to dict
The Entity.to_dict function has a related_objects keyword argument. You can use it to include the objects in the dicts.
Read more >The to_dict function does not include NER fields for tokens #361
When using the to_dict function I would expect the resulting list of dicts to include NER information but they do not.
Read more >pandas.DataFrame.to_dict — pandas 1.5.2 documentation
Convert the DataFrame to a dictionary. The type of the key-value pairs can be customized with the parameters (see below). ... Determines the...
Read more >NDB Model Class - App Engine standard environment
A class that inherits from Model describes Datastore entities. ... The property definitions in the class body tell the system the names and...
Read more >API Reference — Pony ORM documentation
Registers function that will be called each time new connection for given ... In this case Pony will insert into the table associated...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
This is a pretty old Issue, and I apologize I didn’t read over this as carefully as I should. But I created a function to do recursive to_dict(). I’ve only worked it for my own very specific needs, but hopefully it will provide some inspiration for someone more technically inclined than myself.
https://gist.github.com/Kamori/2b574057e9f514732e9c9296136d7929
Hi @kozlovsky, are there any plans to implement any kind of recursive to_dict()?