Question

I have the current model in MongoEngine:

class Comment(EmbeddedDocument):
    content = StringField()
    pub_date = DateTimeField()

class Post(Document):
    title = StringField()
    comments = SortedListField(EmbeddedDocumentField(Comment))
    post_date = DateTimeField()

I get all my posts like this:

posts = Post.objects.all()

and I can then iterate through the posts and then comments but getting the post.comments list.

But I'm not sure how to sort the list of comments for each post by date. I know the comments are chronologically added by default but how do I switch between ascending/descending order of comments, i.e. newest comment first?

I've tried the meta property to no avail:

meta = {
    'ordering': ['-pub_date']
}

Thoughts?

Was it helpful?

Solution

SortedListField makes sure the collection is sorted before writing to the database so mongo in this case doesn't do any sorting. If you have them sorted chronologically, why don't you just revert the list to iterate in the reverse chronological order? :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top