[Answered ]-Django: How to get/set model field value if it is put into any data structure?

2👍

The reason it doesn’t work is because you are referring to field objects themselves in your votes variable. Your code is doing the same thing as models.IntegerField(default=0) + 1 which is of course invalid.

The simplest solution is to simply get/set new attributes and let the django magic deal with the fields -> value conversions.

def add_vote(self,choice):
    attname = 'votes_{0}'.format(choice) # get the attribute name
    value = getattr(self, attname) # get the value
    setattr(self, attname, value+1) # set the value

If you want to use this votes field of yours to determine index / field, you can access Field.attname to figure out the attribute name of your field.

def add_vote(self,choice):
    attname = self.votes[choice].attname
    value = getattr(self, attname) # get the value
    setattr(self, attname, value+1) # set the value

Leave a comment