Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 526
Shehzad009 Avatar asked Jul 13 '11 21:07

Shehzad009


2 Answers

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.

like image 70
Fitoria Avatar answered Sep 18 '22 13:09

Fitoria


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

like image 27
GaretJax Avatar answered Sep 18 '22 13:09

GaretJax