On Tue, Jan 26, 2010 at 5:23 PM, Wim De Hul <w...@dehul.com> wrote:

> Dear list members,
>
> I have a table:
>
>    user | max_volume | used_volume | expire_date
>
> I have to select the rows from the table where max_volume > used_volume and
> data > now
>
> Is this possible without creating custom SQL and without any intermediate
> steps?
>

Given this model (from which I left out user since you did not reference it
in your query):

class Volstat(models.Model):
    max_volume = models.IntegerField()
    used_volume = models.IntegerField()
    expire_date = models.DateField()

    def __unicode__(self):
        return u'Expires %s, max = %s, used = %d' % (self.expire_date,
self.max_volume, self.used_volume)

I think the query at the end here does what you want.  (I've assumed where
you said data > now you meant expire_date > today.)

>>> from ttt.models import Volstat
>>> import datetime
>>> today = datetime.date.today()
>>> yesterday = today - datetime.timedelta(1)
>>> tomorrow = today + datetime.timedelta(1)
>>> Volstat.objects.create(expire_date=yesterday, max_volume=5,
used_volume=5)
<Volstat: Expires 2010-01-25, max = 5, used = 5>
>>> Volstat.objects.create(expire_date=yesterday, max_volume=5,
used_volume=4)
<Volstat: Expires 2010-01-25, max = 5, used = 4>
>>> Volstat.objects.create(expire_date=yesterday, max_volume=5,
used_volume=3)
<Volstat: Expires 2010-01-25, max = 5, used = 3>
>>> Volstat.objects.create(expire_date=tomorrow, max_volume=5,
used_volume=3)
<Volstat: Expires 2010-01-27, max = 5, used = 3>
>>> Volstat.objects.create(expire_date=tomorrow, max_volume=5,
used_volume=4)
<Volstat: Expires 2010-01-27, max = 5, used = 4>
>>> Volstat.objects.create(expire_date=tomorrow, max_volume=5,
used_volume=5)
<Volstat: Expires 2010-01-27, max = 5, used = 5>
>>> from django.db.models import F
>>>
Volstat.objects.filter(max_volume__gt=F('used_volume'),expire_date__gt=today)
[<Volstat: Expires 2010-01-27, max = 5, used = 3>, <Volstat: Expires
2010-01-27, max = 5, used = 4>]
>>>

Documentation on F expressions is here:

http://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model

Karen

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to