Soviet
Soviet

Reputation: 119

-timestamp in Django

I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding:

class Meta:
    ordering = ('-timestamp',)

in views.py. Unfortunately, it changes nothing - my posts are not moving. The book is not very descriptive about that. Do I have to register this class somewhere? I want my pseudo-blog to be pwetty! :P

Thanks in advance.

Upvotes: 2

Views: 1118

Answers (4)

user470379
user470379

Reputation: 4879

Without any more information, I believe the solution to your problem is that the class Meta declaration needs to be in whatever model represents the blog entry (likely in models.py, not views.py). Also, double-check that timestamp is the name of the field in the BlogEntry class that stores the date/time of the blog entry.

class BlogEntry:
    class Meta:
        ordering = ('-timestamp',)

    #rest of the BlogEntry class

Upvotes: 0

Nedec
Nedec

Reputation: 836

You have to add Meta to your Model (rather than to the views.py):

class Post(models.Model):
    title = models.CharField()
    timestamp = (...)

    class Meta:
        ordering = ['-timestamp']

Now, whenever you get your Posts they will be ordered by -timestamp.

If you want to learn more about Meta options, take a look at the documentation.

Upvotes: 1

Robert
Robert

Reputation: 6540

There's a few ways to do this. By adding a Meta class, you give the object an inherent ordering. Using the manager to get all() will return you a list-like group of every object, in order. I haven't tested it myself but the list you get from a filter() ought to be in order too.

Now, you can also order at the time of the query:

BlogEntry.objects.all().order_by('-timestamp')

will sort by descending timestamp.

Note that these both presuppose a field in your model called 'timestamp' that contains a sortable field (like a DateTimeField, probably, in this case)

If adding the Meta didn't change your order, I suspect you're sorting by something else, somewhere else. How about posting the query that should generate the sorted list?

Upvotes: 1

gruszczy
gruszczy

Reputation: 42168

You would have to present some more code, for example how you retrieve data from database. Here you have some ordering examples:

http://www.djangoproject.com/documentation/models/ordering/

Upvotes: 1

Related Questions