django getattr and issues with updating
<p>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:</p>

<pre><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
</code></pre>

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

<pre><code>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
</code></pre>

<p>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.</p>

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

<p>Thanks</p>

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

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

<p>Note that you would get <em>exactly</em> the same result if you originally did <code>call = workingobj.fieldname</code>.</p>

python django django-models getattr