[Fixed]-Django queryset element can't be changed?

1👍

Currently, Django is doing a separate query to fetch each individual dataset[i], and a final query when dataset is evaluated.

The solution is to to force the queryset to be evaluated by converting it to a list. You’ll have to use len() instead of count().

def cumulate(self, dataset):
    dataset = list(dataset)
    nb = 0
    for i in range(len(dataset)):
        nb += dataset[i]['nb']
        dataset[i]['nb'] = 99
        print(dataset[i]['nb'])
    return dataset

It would be more pythonic to iterate over the queryset instead of looping over the range. In this case, looping over the queryset will cause it to be evaluated, and I don’t think you’ll have to convert it to a list.

def cumulate(self, dataset):
    nb = 0
    for d in dataset:
        nb += d['nb']
        d['nb'] = 99
        print(d['nb'])
    return dataset

Leave a comment