Django: want to sort comments by datetime

16,265

Solution 1

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

Solution 2

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.

Solution 3

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.

Share:
16,265

Related videos on Youtube

Shehzad009
Author by

Shehzad009

Updated on June 04, 2022

Comments

  • Shehzad009
    Shehzad009 almost 2 years

    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)
    
  • Shehzad009
    Shehzad009 almost 13 years
    I am assuming this is what I need. comments = Comment.objects.order_by('-datetime')
  • kaxi1993
    kaxi1993 almost 4 years
    You are missing comma ordering = ('-datetime',)