Django: want to sort comments by date

I have comments and I want to sort them with the last comment at the top of the list. However, it does not work. I get this error.

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

I am not sure what causes this problem. Here are my views and model that may help.

Views

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

model

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)
+5
source share
3 answers

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

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

+7

meta , :

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)

, .

"datetime" , datetime - python, .

+6

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

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

+2
source

All Articles