Search code examples
pythondjangodjango-modelsgetattr

django getattr and issues with updating


In django I built a simple method that gets called and is passed a uniqueid, field specifier, and a value. It then does a simple addition to update the value in the field. I've coded it a number of ways and have come to the conclusion that getattr does not work when trying to save, update, or refresh the database. One variation of my code:

def updatetable(uid, fieldtitle, value):
    workingobj = bog_db.objects.get(name=uid)
    objectcall = getattr(workingobj,fieldtitle)
    objectcall = F(fieldtitle) + value
    workingobj.refresh_from_db()
    return

I tried hand jamming some code to see if I could figure out the problem. btw: value = 37

In [36]: call = getattr(workingobj,fieldname)

In [37]: call
Out[37]: 37

In [38]: call += value

In [39]: call
Out[39]: 74

In [40]: workingobj.save()
#refreshed database, checked table, values in db not updated
In [41]: workingobj.total_number_posts += value

In [42]: workingobj.total_number_posts
Out[42]: 74

In [43]: workingobj.save()
#refreshed database, values in db were updated

It would appear to me that Django does not want you using getattr for doing db calls and updates and instead wants you to EXPLICITLY call object.field.

Is this true? Does getattr make a copy of the attributes? I want to better understand why it is behaving this way.

Thanks


Solution

  • I'm not sure what you're expecting here, but this is nothing to do with Django wanting anything, and nothing to do with setattr.

    Integers are immutable. However you get the value of fieldname and store it in call, you cannot modify it. Doing call += value creates a new value and stores it in call; that now has no relationship with the original value of fieldname.

    Note that you would get exactly the same result if you originally did call = workingobj.fieldname.