Django, Python, trying to change field values / attributes in object retrieved from DB objects.all call, not working

24,772

I'm not sure if this is the problem or not, but I think you might be missing a save() method.

from models import Person
p = Person.objects.get(pk=100)
p.name = 'Rico'
p.save()      # <== This writes it to the db. Is this what you're missing?

Above is the simple case. Adapted for what you wrote above, it'd be like:

dbobject.dbobject[0].fieldname = 'some new value'
dbobject.dbobject[0].save()

or, I'd write it more like:

rec = dbobject.dbobject[0]
rec.fieldname = 'some new value'
rec.save()

Also note that depending on whether and how you are using transactions, you may or may not see a change to the database until you commit.

Share:
24,772
Rick
Author by

Rick

Web programmer with an interest in web task automation, building websites, etc, I prefer to do everything in Python now as I have moved to it from using a variety of other languages in the past. I also like to do front-end AJAX / javascript work but am moving to do this through Python as well, with the Pyjamas framework.

Updated on July 09, 2022

Comments

  • Rick
    Rick almost 2 years

    I'm trying to change a specific field from a field in an object that I retrieved from a django db call.

    class Dbobject ()
       def __init__(self):
           dbobject = Modelname.objects.all()
       def test (self):
           self.dbobject[0].fieldname = 'some new value'
    

    then I am able to access a specific attribute like so:

    objclass = Dbobject()
    fieldvalue = dbobject.dbobject[0].fieldname
    

    but I want to be able to use the "test" method of the Dbobject class to try to change the specific value on an object's attribute value, but it isn't changing it. I am stumped by this as this is how I thought I am supposed to change an object's attribute value.