0

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.

Krisnadi
  • 641
  • 1
  • 10
  • 23
  • First of all, wallet1 is field of class Wallet and 'wallet1' is a string. How do you expect Django to understand that by string 'wallet1' you actually are referring to wallet1 of Wallet. Plus, its obvious that you get object has no attribute error. Also, whats wrong with obj.wallet1 = obj.wallet1 - amount – Rajesh Yogeshwar May 11 '16 at 09:01
  • You should use setattr and getattr. setattr(obj, field_obj, value) – durdenk May 11 '16 at 09:09
  • @RajeshYogeshwar i do that because i get the 'wallet1' from my front end with request.data['transfer_from']. So i put the data from front end into a variable. – Krisnadi May 11 '16 at 09:09
  • @durdenk Can you show me some sample code or a link? – Krisnadi May 11 '16 at 09:09

3 Answers3

2

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
Community
  • 1
  • 1
Julien Salinas
  • 1,059
  • 1
  • 10
  • 23
2

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()
durdenk
  • 1,590
  • 1
  • 14
  • 36
  • the getattr is working, but unfortunately the setattr doesn't work. do you know what is the problem? – Krisnadi May 11 '16 at 09:39
1
setattr(obj, transfer_form, getattr(obj, transfer_form) - amount)

getattr, setattr.

vsd
  • 1,473
  • 13
  • 11