views:

87

answers:

2

I have this line of code in my views that allows me to display a group of items by date (I've also reversed the order so the most recent displays first):

currentlinks = Current.objects.order_by('date_added').reverse()[:5]

this works fine —

however, when I concatenate the "order_by" code with a filter...

currentsources = Current.objects.filter(source__exact='bbc').order_by('date_added')

this doesn't work? does anyone know why? poor syntax perhaps, or am I just not understanding how this is supposed to work?

+1  A: 

If there are no Current objects with a source of "bbc", then you will of course get an empty result set. Is that what you mean by doesn't work? If not, please post the results you do get.

Update: One more thing to try: fire up

manage.py shell

and then in the shell, evaluate the queryset which is giving the problem.

currentsources = Current.objects.filter(source__exact='bbc').order_by('date_added')

Then, do the following:

from django.db.import connection
connection.queries

and this will show the raw SQL which is executed for the queryset. It should help home in on the issue.

Vinay Sajip
hi Vinay,it returns the objects, but they are not ordered by date. in fact, i can't tell how they're ordered - seems random (although, I'm sure it's not.)
hi Vinay AND Daniel.
So exactly what type is the `date_added` property of your `Current` model?
Vinay Sajip
date_added = models.DateField(auto_now_add=True)
will execute instructions and investigate from there. thanks for your assistance.
A: 

One thing that I noticed in your query: if you're trying to reverse the order so that more recent dates appear first, you would use the following syntax:

currentlinks = Current.objects.order_by('-date_added')

The minus sign in front on the field reverses the order. It equates roughly to the following syntax in SQL:

SELECT * FROM current_links ORDER BY date_added DESC

The order_by() should work if you chain it after a filter(), provided that the filter() is valid.

Jim McGaw