> Hi,
>
> I have trouble getting a QuerySet to do what I want. I need to select
> the last 10 items of a certain model (ordered by timestamp; so the
> "most recent" 10 items), and when I iterate over them during template
> processing I want the earliest item (with the oldest timestamp) to
> come first.
>
> I've tried to achieve this using various combinations of slicing,
> reverse(), and ordering on 'timestamp' vs '-timestamp', but I can't
> get it to work.
>
> How can this be done?
>
> Regards, Sidney
>
Unless I'm being dense, you cannot represent this as a single SQL
query, so logically you cannot represent this as a QuerySet. Dropping
to a little python, it is trivial:
>>> q=UsageLogEntry.objects.all().order_by('-time')[:10]
>>> items = list(q)
>>> items.reverse()
>>> for l in items: print l.time
...
2011-03-02 14:18:16
2011-03-02 14:18:23
2011-03-02 14:50:15
2011-03-02 15:24:16
2011-03-02 15:24:16
2011-03-02 15:24:23
2011-03-03 11:23:42
2011-03-03 11:28:49
2011-03-03 11:28:52
2011-03-04 12:30:15
If you absolutely must have a queryset, you can fudge it with two queries:
>>> q=UsageLogEntry.objects.all().order_by('-time')[:10]
>>> q_ids = list(q.values_list('id', flat=True))
>>> items = UsageLogEntry.objects.filter(id__in=q_ids).order_by('time')
>>> for l in items: print l.time
...
2011-03-02 14:18:16
2011-03-02 14:18:23
2011-03-02 14:50:15
2011-03-02 15:24:16
2011-03-02 15:24:16
2011-03-02 15:24:23
2011-03-03 11:23:42
2011-03-03 11:28:49
2011-03-03 11:28:52
2011-03-04 12:30:15
Cheers
Tom
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
No comments:
Post a Comment