Django: want to sort comments by datetime
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
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.