Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a QuerySet object on the fly in Django

Can or should I ever do this in a view?

a = SomeTable.objects.all()
for r in a:
    if r.some_column == 'foo':
        r.some_column = 'bar'

It worked like a champ, but I tried a similar thing somewhere else and I was getting strange results, implying that QuerySet objects don't like to be trifled with. And, I didn't see anything in the docs good or bad for this sort of trick.

I know there are other ways to do this, but I'm specifically wanting to know if this is a bad idea, why it's bad, and if it is indeed bad, what the 'best' most django/pythonic way to change values on the fly would be.

like image 410
proffrink Avatar asked Mar 15 '12 01:03

proffrink


1 Answers

This is fine as long as you don't do anything later that will cause the queryset to be re-evaluated - for example, slicing it. That will make another query to the database, and all your modified objects will be replaced with fresh ones.

A way to protect yourself against that would be to convert to a list first:

a = list(SomeTable.objects.all())

This way, further slicing etc won't cause a fresh db call, and any modifications will be preserved.

like image 72
Daniel Roseman Avatar answered Oct 15 '22 21:10

Daniel Roseman