Reputation: 681
I want to update a record, but the field is determined by string. Is it possible to do so?
This is my model:
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)
This is my code:
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 only recognize the field when i write this:
obj.wallet1 = obj.wallet1 - amount
but it doesn't recognize this:
transfer_from = 'wallet1'
obj.transfer_from = obj.transfer_from - amount
Is said 'Wallet' object has no attribute 'transfer_from'. Thank you.
Upvotes: 1
Views: 1615
Reputation: 1139
Actually this is a Python question. Please refer to this: What is getattr() exactly and how do I use it?
Using getattr
, here is what you could do:
transfer_from_label = 'wallet1'
transfer_from = getattr(obj, transfer_from_label)
transfer_from = transfer_from - amount
Upvotes: 2
Reputation: 1660
This is not tested but should work.
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()
Upvotes: 3