I
I
IvanOne2015-11-15 09:49:35
Django
IvanOne, 2015-11-15 09:49:35

Django F+update not updating a field?

Django 1.8, postgre base.
There is a Wallet model with a balance field, and there is a method that updates it

def update_balance(self, amount):
        Wallet.objects.filter(pk=self.pk).update(balance=models.F("balance")+amount)
        return

Create wallet self.wallet = Wallet.objects.create(user=self.user, currency=self.currency, balance=10000)
test:
def test_change_wallet_balance(self):
        amount = 5000
        self.wallet.update_balance(amount)
        self.assertEqual(self.wallet.balance, 15000)

I get the error
self.assertEqual(self.wallet.balance, 15000)
AssertionError: Decimal('10000') != 15000
the balance field is a decimal field
How to implement the method correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Klimenko, 2015-11-15
@IvanOne

You need this https://docs.djangoproject.com/en/1.8/ref/models/i...
You have an instance of the model (representation in the form of a python object of the record from the database), when you do an update, you update the data in the database itself, while the model instance was what it was and remained.

S
sim3x, 2015-11-15
@sim3x

self.assertEqual(self.wallet.balance, Decimal(15000))

I hope the wallet is just a euphemism and has nothing to do with money

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question