Tuesday, March 1, 2011

Django ORM query modelling question

Dear Django list,

after a very good start with Django and it's excellent documentation,
I've come now across a problem that neither my SQL nor my Django
knowledge is sufficient to solve, so I'd like to ask for your kind help.

The (simplified) Django model is


class Erfasst(models.Model):
datum = models.DateField()
info = models.BigIntegerField()


An example for the contents of this model is, pre-sorted by 'datum':

datum info
-----------------------
2011-FEB-01 4 *
2011-FEB-02 4
2011-FEB-03 4
2011-FEB-04 5 *
2011-FEB-05 5
2011-FEB-06 5
2011-FEB-07 5
2011-FEB-08 1 *
2011-FEB-09 1
2011-FEB-10 4 *
2011-FEB-11 4


What I would like to know are the rows, when ordered by 'datum', whose
'info' changed (those marked with a star above).


I tried

Erfasst.objects.values('info').annotate(Min('datum'))

but that doesn't work, because it groups all rows with e.g. 'info'==4
and thus doesn't report the row with (datum: 2011-FEB-10, info: 4).

Erfasst.objects.order_by('datum').values('info').annotate(Min('datum'))

doesn't work either, because it groups the ('datum', 'info') pairs,
which is one row per group.


What is the correct query for the task?

Thank you very much!

Best regards,
Carsten

No comments:

Post a Comment