Shehzad009
Shehzad009

Reputation: 1607

Django: want to sort comments by datetime

I have in my view comments and I want to sort them with the latest comment at the top of the list. However it is not working. I get this error.

Caught TypeError while rendering: 'Comment' object is not iterable

I am not so sure what is causing this problem. Here is my views and model which may help.

Views

def home(request):
    comments = Comment.objects.latest('datetime')
    return render_to_response('home.html', {'comments':comments}, context_instance=RequestContext(request))

models

class Comment(models.Model):
    name = models.CharField(max_length = 40)
    datetime = models.DateTimeField(default=datetime.now)
    note = models.TextField()
    def __unicode__(self):
        return unicode(self.name)

Upvotes: 8

Views: 17459

Answers (3)

Fitoria
Fitoria

Reputation: 595

The cleanest way is to add a class meta to your model and add the ordering parameter like this:

class Comment(models.Model):
    name = models.CharField(max_length = 40)
    datetime = models.DateTimeField(default=datetime.now)
    note = models.TextField()

    class Meta:
        ordering = ['-datetime']
       
    def __unicode__(self):
        return unicode(self.name)

So every query you make will be ordered by datetime.

Another advice do not choose "datetime" as a field name, datetime is a python module included in the standard lib.

Also see Django ordering docs here.

Upvotes: 14

GaretJax
GaretJax

Reputation: 7780

The latest method returns only one object, not an iterator: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest

Use the order_by method to order them by date (first example in the doc): https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.order_by

Upvotes: 11

Ram
Ram

Reputation: 1161

Comment in comments = Comment.objects.latest('datetime') is NOT a collection of comment; it is a single comment.

What you want to do is create an array of Comment objects and iterate through that.

Upvotes: 2

Related Questions