1

I have following structure with example data:

id   season_id    title 
1    1            Intro
2    1            Second part
3    1            Third part
4    4            Other intro
5    4            Other second part

(don't ask why), where season_id is always point to id of first episode of season...

What i want, to get following:

1    1            Intro
4    4            Other intro

which are first episoded for season, technically speaking - all entries with lowest season_eid

for and i am using following query to get ids of them:

Movie.objects.filter(category_type = 2).values('season_eid').annotate(models.Min('season_eid'))

and having id i can get all data for objects using django orm __in construction.

Can I make grouping / annotate and take all fields/values using only one query? values + annotate gives me only list of dictionaries, but instead of this i would like to get proper objects (lowest value/min of season_eid) with rest of fields.

bluszcz
  • 4,054
  • 4
  • 33
  • 52
  • Yes, it is possible. But you should include a little more models info, for eg, the foreign keys and category, for us to be able to assist – lprsd Feb 23 '10 at 12:47
  • Ok, forget about Foreign Keys and "category_type" - I am only interested in seasons. – bluszcz Feb 23 '10 at 14:53
  • Look at my updated answer. Its pretty simple actually. – lprsd Feb 24 '10 at 10:43

1 Answers1

1
Movie.objects.annotate(category_min_season = models.Min('category__season_id')).filter(season_id=category_min_season)

assuming that your catgory has FK to the Movies model.

Update:

Actually you don't even need annotation; thanks to the denormalised data you have stored in the table.

You can just do:

Model.objects.filter(id=Q(season_id))
lprsd
  • 84,407
  • 47
  • 135
  • 168