TotuDoum
TotuDoum

Reputation: 137

django change field by variable

I have this:

class Character(models.Model):
    weapon = models.ForeignKey(item, related_name='weapon')
    shield = models.ForeignKey(item, related_name='shield')
    ...

class Item(models.Model):
    nom = models.CharField(max_length=30)
    choices = (
        ('weapon', 'weapon'),
        ('shield', 'shield'),
        ...
    )
    typeOf = models.CharField(max_length=15, choices=choices)
    ...

I would like to update my character field by the name of the item.typeof like this but it doesn't work.

character[item.typeof] = item
character.save()

how do I do this?

Upvotes: 0

Views: 772

Answers (1)

catavaran
catavaran

Reputation: 45555

Use built-in setattr() function:

setattr(character, item.typeOf, item)
character.save()

Upvotes: 3

Related Questions