Mongoengine更好地查询更新列表字段中的嵌入文档

时间:2015-08-18 10:04:40

标签: python mongodb django-rest-framework mongodb-query mongoengine

以下是我编写的函数,它将对话框文档中某个成员的成员嵌入文档的“new_messages”标志设置为true。

def check_and_update_new_messages_flag(self, pk, user):
    conversation = Conversation.objects.with_id(pk)
    if conversation is None:
        raise ConversationNotFoundException
    messages = Message.objects(conversation=pk).count()
    messages_viewed_by_user = Message.objects(conversation=pk, viewed_by=user).count()
    if messages == messages_viewed_by_user:
        for index, member in enumerate(conversation.members):
            if member.user == user:
                member = Members()
                member.user = user
                conversation.members[index] = member
                conversation.save()
        conversation.update()

我正在创建一个Members对象并在匹配发生的索引处替换成员对象,只是将new_messages标志更新为false(在模型中设置为默认值)。是否有更好的查询来执行此任务。我不想要额外的循环和if语句,以使这个功能更有效。

编辑: 模特:

class Members(EmbeddedDocument):
    user = ReferenceField(User)
    new_messages = BooleanField(default=False)


class Conversation(Document, MboBaseDocument):
    opportunity = ReferenceField(Opportunity)
    members = ListField(EmbeddedDocumentField(Members))
    counts = EmbeddedDocumentField(Counts)
    status = StringField(required=True, default='active', regex='closed|active')
    responded_on = IntField(required=True)
    created_by = ReferenceField('User', required=True)
    updated_at = IntField()

此外,样本文件:

{
    "_id" : ObjectId("55c37053aee967157371372e"),
    "opportunity" : ObjectId("55a3907c8c5bf672f4ad31b8"),
    "members" : [ 
        {
            "user" : ObjectId("5579a6b38c5bf602374b9a0b"),
            "new_messages" : true
        }, 
        {
            "user" : ObjectId("abcdef12345abcdef1234503"),
            "new_messages" : true
        }, 
        {
            "user" : ObjectId("5581168c45910c43912e6a01"),
            "new_messages" : true
        }
    ],
    "counts" : {
        "members" : 3,
        "messages" : 6
    },
    "status" : "active",
    "responded_on" : NumberLong(1438871635000),
    "created_by" : ObjectId("abcdef12345abcdef1234503"),
    "updated_at" : NumberLong(1439194817000)
}

0 个答案:

没有答案