Created
November 15, 2019 23:47
-
-
Save drozdowsky/617b5ce4a2404c0dbaa2d0c4dc57dc82 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from app.models import SomeModel | |
from collections import defaultdict | |
def tree_from_values(queryset, parent_field_id): | |
root = defaultdict(lambda: defaultdict(list)) | |
for d in queryset: | |
# no need to pop but we don't need it anyway | |
parent = d.pop(parent_field_id) | |
pk = d['pk'] | |
root[pk].update(d) | |
root[parent]['_children'].append(root[pk]) | |
return root[None] | |
queryset = SomeModel.objects.values('pk', 'parent_id', 'some_other_field') | |
roots = tree_from_values(queryset, 'parent_id')['_children'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment