所以我想要的是这样的:
class Comment(EmbeddedDocument):
content = StringField()
upvotes = IntField()
pub_date = DateTimeField()
class Post(Document):
title = StringField()
comments = SortedListField(EmbeddedDocumentField(Comment))
post_date = DateTimeField()
默认情况下,这是按评论提交的时间顺序排序的,但我想让 SortedListField
按嵌入评论文档的 upvotes
属性排序。这可能吗?如果可以,我该怎么做?
最佳答案
这实际上已在 unit tests 中进行了介绍。如果不清楚 documentation本身:
class Post(Document):
title = StringField()
comments = SortedListField(EmbeddedDocumentField(Comment)
ordering="upvotes", reverse=True)
post_date = DateTimeField()
因此,添加“ordering”关键字允许字段在更改指定项目时进行排序。您可能还希望反向语句确保最高的“upvotes”值也排在第一位。
单元测试实际上也显示了一些其他用法,因此始终是找出可能晦涩的用法的好来源。
关于python - Mongoengine:如何按嵌入式文档字段对嵌入式文档列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22997738/