Question

So what I'm after is something like:

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

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

By default, this sorts by the chronological order of comment submission, but I want to make the SortedListField sort by the upvotes attribute of the embedded comment documents. Is this possible, and if so how do I go about it?

Was it helpful?

Solution

This is actually covered in the unit tests if not clear from the documentation itself:

class Post(Document):
    title = StringField()
    comments = SortedListField(EmbeddedDocumentField(Comment)
                               ordering="upvotes", reverse=True)
    post_date = DateTimeField()

So adding the "ordering" keyword allows the field to sort on when the items are changed to be specified. You probably also want the reverse statement to make sure the highest "upvotes" value is first as well.

The unit tests actually show some other usages as well so are always a good source for finding out possibly obscure usages.

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