django按变量改变字段

时间:2015-01-29 10:57:45

标签: django model foreign-keys

我有这个:

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)
    ...

我想通过item.typeof的名称更新我的字符字段,但它不起作用。

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

我该怎么做?

1 个答案:

答案 0 :(得分:3)

使用内置setattr()功能:

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