I would like to store certain fields from a QuerySet object into a python object (e.g. dictionary), but I wonder if it is possible to do this without looping, at least explicitly, in Python?
For example, if the content of the QuerySet are as follows:
>> queryset.values_list('parents', 'children', 'x', 'y')
>> [('parent1', 'child1', 1.1, 1.03), ('parent1', 'child2', 1.4, 1.05), ('parent2', 'child1', 0.1, 0.2), ('parent2', 'child2', 1.3, 2.2)]
Now, I would like to convert this into a dictionary. The actual structure of the dictionary is of secondary importance, as long as all the information is contained. E.g.:
d = {
'child1': {
'parent1' : [1.1, 1.03],
'parent2' : [0.1, 0.2],
...
}
# or
d = {
'parent1': {
'child1': [1.1, 1.03],
'child2': [1.4, 1.05]
...
}
# or even:
d = {
'child1': [
# parent1 # parent2
(1.1, 1.03), (0.1, 0.2)
]
...
}
Of course, I can do this if I loop through the queryset in Python, but is it really necessary to do an explicit for loop? Is there a way to populate the dictionary directly from the queryset, similar to how list(queryset) gives you a list?
I mostly worry that a for loop will not scale well in terms of performance if I need to retrieve tens of thousands of similar entries. I know that possibly iteration is unavoidable, but at least I'd like to avoid doing that explicitly.
Everything I found online shows how to do this by iterating over the queryset in Python, which is clear to me, but I wonder if there are other, perhaps more performant, ways of doing this.
valuesmethod? docs.djangoproject.com/en/4.1/ref/models/querysets/…