views:

504

answers:

2

Hi there,

Given an object like:

class M(models.Model):
  test = models.BooleanField()
  created_date = models.DateTimeField(auto_now_add=True)

Given sample data (assume monotonically increasing automatic created_date):

M(test=False).save()

M(test=True).save()

M(test=False).save()

X = M(test=True).save()

M(test=False).save()

Y = M(test=False).save()

M(test=False).save()

M(test=True).save()

Can one use the Django ORM to create a query that would return X (the previous query, by date, where 'test'=True), if you are given Y? If so, how?

In other words: Given Y, how does one get the most recent previous element where 'test' is True?

Thoughts & feedback is appreciated, thanks!

+3  A: 

With the help of Django field lookups, you may be able to achieve something to the effect of what you want with the following expression:

M.objects.filter( test=True, created_date__lt=Y.created_date ).order_by( '-created_date' )

Depending on whether there are or are not any elements in the resulting queryset object, you may pick up the very first one which will be the most recent object that you want.

ayaz
+5  A: 

Try this

M.objects.filter(created_date__lte=Y.created_date).filter(test=True)[0:1]

You can also add an order_by clause like

M.objects.filter(created_date__lte=Y.created_date)\
         .filter(test=True)\
         .order_by('-created_date')[0:1]

This should work.

Baishampayan Ghose