I’m trying to do something like that:
class PollResults(models.Model):
votes_0 = models.IntegerField( default=0 )
votes_1 = models.IntegerField( default=0 )
votes_2 = models.IntegerField( default=0 )
votes_3 = models.IntegerField( default=0 )
votes = [votes_0,votes_1,votes_2,votes_3]
def add_vote(self,choice):
self.votes[choice] = self.votes[choice]+1
But, when I call add_vote(0), I am getting: “unsupported operand type(s) for +: ‘IntegerField’ and ‘int'”.
Is there any way to make it working? Please don’t criticize the database design, this is just an example. The point is how to get/set the field value.
The reason it doesn’t work is because you are referring to field objects themselves in your
votesvariable. Your code is doing the same thing asmodels.IntegerField(default=0) + 1which 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.
If you want to use this
votesfield of yours to determine index / field, you can accessField.attnameto figure out the attribute name of your field.