[Fixed]-Django queryset orm – from same table fetch data in particular format

1👍

The query is simple:

bs = B.objects.select_related('emp', 'y').order_by('emp__username', 'z')

These B instances have all the information you need. For a start you could do:

from itertools import groupby
user_dct = {k: list(g) for k, g in groupby(bs, lambda b: b.emp.username)}
user_dct
{'user1': [b1, b2], 'user2': [b3], 'user3': [b4, b5]}

and go from there…

Leave a comment