我希望在将文档嵌入到其他文档之前为文档添加额外的属性,但我不知道该怎么做。
这是我的代码以及到目前为止我尝试过的内容:
from mongoengine import *
from datetime import datetime
class User(Document):
name = StringField(max_length=80, required=True)
created_at = DateTimeField(default=datetime.now(), required=True)
updated_at = DateTimeField(default=datetime.now(), required=True)
meta = {
'collection': 'users'
}
def save(self, *args, **kwargs):
self.updated_at = datetime.now()
return super(User, self).save(*args, **kwargs)
class Stream(Document):
users = EmbeddedDocumentListField(document_type='User')
created_at = DateTimeField(default=datetime.now(), required=True)
updated_at = DateTimeField(default=datetime.now(), required=True)
meta = {
'collection': 'streams'
}
def save(self, *args, **kwargs):
self.updated_at = datetime.now()
return super(Stream, self).save(*args, **kwargs)
当我将user document
嵌入到用户EmbeddedDocumentListField
时,它会被添加,看起来像这样
{
"_id" : ObjectId("57e6123fe8c39b18b1a13431"),
"users" : [
{
"_id" : ObjectId("57e6123fe8c39b18b1a13432"),
"name": "Rohit Khatri",
"created_at" : ISODate("2016-09-24T11:12:23.182Z"),
"updated_at" : ISODate("2016-09-24T11:12:23.301Z")
}
],
"created_at" : ISODate("2016-09-24T11:12:23.189Z"),
"updated_at" : ISODate("2016-09-24T11:12:23.323Z")
}
现在我想在User文档中嵌入其他属性,比如角色。这是我尝试过的: -
user = User.objects.create(name='Rohit Khatri')
user.roles = ['admin','writer']
stream = Stream.objects.create()
stream.users.append(user)
stream.save()
但它没有添加角色字段,如果有人可以帮助我,我将感激不尽。
由于
答案 0 :(得分:1)
使用update方法设置新属性
user.update(set__roles = ['admin','writer'])