ModulusJoe
ModulusJoe

Reputation: 1456

Django Object Get on Decimal Match

I have a Django model WalletJournal which has a number of fields that are Decimal values, and example model class definition looks like:

balance  = models.DecimalField(max_digits=20,decimal_places=2)

The corresponding mysql column is defined as:

`balance` decimal(20,2) NOT NULL,

And when retrieving a row by its id and returning the balance it looks correct.

>>> WalletJournal.objects.get(id=855).balance
Decimal('1295599062.45')
>>>

I am attempting to use a get_or_create to add entries and keep the duplicates to a minimum, but I am seeing some very stange behaviour on the get on decimals. Trying to match view either string or Decimal returns no results:

>>> WalletJournal.objects.get(balance='1295599062.45')
DoesNotExist: WalletJournal matching query does not exist.
>>> WalletJournal.objects.get(balance=Decimal(str('1295599062.45')))
DoesNotExist: WalletJournal matching query does not exist.

But if I match using __iexact I get the correct result:

>>> WalletJournal.objects.get(balance__iexact='1295599062.45')
<WalletJournal: joeb - 1XXXX00 - Acyclic Tau(9XXXX307) - Repair Bill(2013-11-30 15:55:01)>

I don't believe __iexact is not a perfect solution, if somebody could suggest what I am doing wrong that would be very helpful.

I am currently running Django 1.6 and Python 2.6.5. MySQL Server version: 5.1.72-0ubuntu0.10.04.1 (Ubuntu)

Using connection.queries I can see the following queries results from the various get statements:

__iexact       --> `balance` LIKE '1295599062.45' : Matches
__exact        --> `balance` = '1295599062.45'    : No Match
str            --> `balance` = '1295599062.45'    : No Match
Decimal(str(   --> `balance` = '1295599062.45'    : No Match
Raw SQL        --> `balance` = 1295599062.45      : Matches

Am I doing something wrong with the comparison?

Upvotes: 4

Views: 592

Answers (1)

ModulusJoe
ModulusJoe

Reputation: 1456

This looks to be a bug in the query handling of mysql. I have now tested it successfully in Server version: 5.5.34-0ubuntu0.12.04.1 (Ubuntu) and the query

 WalletJournal.objects.get(balance='1295599062.45')

Now returns results as expected with the query being executed having the following where statement:

`balance` = '1295599062.45'

Upvotes: 1

Related Questions