django model filter

111 views
Skip to first unread message

spearsear

unread,
Sep 2, 2010, 7:00:58 PM9/2/10
to Django users
Account.objects.filter(balance__lt=20) selects accounts with balance
less than $20

Account.objects.filter(balance__lt=jeff.balance) selects accounts with
balance less than the balance of jeff's account

Now, How do I do this?

accounts with balance whose absolute value is greater than the
absolute value of jeff's account balance?

Justin

unread,
Sep 3, 2010, 8:29:19 AM9/3/10
to Django users
Off the top of my head, you could do something like this:

import math
import django.db.models.Q

jeff_abs = math.fabs(jeff.balance) #get the absolute value of jeff's
balance

Account.objects.get(Q(balance__gt=jeff_abs) | Q(balance__lt=(jeff_abs
* -1)))

This way you pick up all positive balances greater than jeff's
absolute balance and all negative balances less than jeff's absolute
balance. This avoids adding a field to your model like 'balance_abs',
which would be just a calculation anyways.

I don't know if this is the cleanest way to do it, but let me know if
it works...

-Justin

spearsear

unread,
Sep 3, 2010, 5:03:57 PM9/3/10
to Django users
I did it in your way, it certainly works.

But I feel this is a little ugly. My query is way more complicated
that the example here so I had to do if a lot.

Justin

unread,
Sep 3, 2010, 7:12:01 PM9/3/10
to Django users
Well, I'm glad it works. Please post, if you want to, a cleaner
solution if you find it!

-Justin
Reply all
Reply to author
Forward
0 new messages