我想更新记录,但该字段由字符串确定。是否可以这样做?
这是我的模特:
class Wallet(models.Model):
user_id = models.IntegerField(blank=True, null=True)
wallet1 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
wallet2 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
这是我的代码:
amount = 200
transfer_from = 'wallet1'
transfer_to = 'wallet2'
obj = Wallet.objects.get(user_id=1)
obj.transfer_from = obj.transfer_from - amount
obj.transfer_to = obj.transfer_to + amount
obj.save()
当我写这个时,Django只识别该字段:
obj.wallet1 = obj.wallet1 - amount
但它不承认这一点:
transfer_from = 'wallet1'
obj.transfer_from = obj.transfer_from - amount
说“钱包”对象没有属性“transfer_from”。谢谢。
答案 0 :(得分:2)
实际上这是一个Python问题。 请参阅:What is getattr() exactly and how do I use it?
使用getattr
,您可以执行以下操作:
transfer_from_label = 'wallet1'
transfer_from = getattr(obj, transfer_from_label)
transfer_from = transfer_from - amount
答案 1 :(得分:2)
这未经过测试但应该有效。
amount = 200
transfer_from = 'wallet1'
transfer_to = 'wallet2'
obj = Wallet.objects.get(user_id=1)
transfer_from_field_val = getattr(obj,transfer_from)
transfer_to_field_val = getattr(obj,transfer_to)
transfer_from_field_val = transfer_from_field_val - amount
transfer_to_field_val = transfer_to_field_val + amount
setattr(obj , transfer_from, transfer_from_field_val)
setattr(obj , transfer_to, transfer_to_field_val)
obj.save()
答案 2 :(得分:1)