damon
damon

Reputation: 8477

creating a django query to get entries of a certain duration

In my django app,an Entry has this model

    from models import PENDING,CLOSED
    class Entry(models.Model):
        ...
        name = models.CharField(max_length=200)
        status = models.CharField(max_length = 4,choices=status_values ,default = PENDING)
        creation_date = models.DateTimeField(default=datetime.datetime.now)           
        closed_date = models.DateTimeField(null=True)

I need to find all Entrys that have a CLOSED status and those that took more than 4 days to close.I am not using any field called duration in the model,but was hoping to compute the difference between closed_date and creation_date as below

(closed_date-creation_date).days

I tried to write the query as

entries = Entry.objects.filter((closed_date-creation_date).days > 4 )

In django shell I tried this

In [9]:Entry.objects.filter((closed_date - creation_date).days > 4)

This produces a NameError:

NameError: name 'closed_date' is not defined

But when I try to get an Entry and access it's closed_date field,

In [9]:  entry1 =  Entry.objects.get(name='myentry')

In [10]: entry1.closed_date
Out[10]: datetime.datetime(2013, 4, 3, 14, 2, 4, 442518)

In [11]: entry1.creation_date
Out[11]: datetime.datetime(2013, 3, 17, 0, 0)

I couldn't figure out what I am doing wrong here..is the query wrong?

Also, when I try this, I get a syntax error:

In [12]: Task.objects.filter(status='CLOSED',(closed_date - creation_date).days > 4)

SyntaxError: non-keyword arg after keyword arg (<ipython console>, line 1)

Upvotes: 0

Views: 59

Answers (1)

Ngenator
Ngenator

Reputation: 11259

You can use the F() expression to compare fields. So you can do something like

entries = Entry.objects.filter(closed_date__gt=F('creation_date') + timedelta(days=4))

Upvotes: 2

Related Questions