質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top