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)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With