使用python dict更新MongoEngine文档? [英] Update a MongoEngine document using a python dict?
问题描述
是否可以使用python字典更新MongoEngine文档?
Is it possible to update a MongoEngine document using a python dict?
例如:
class Pets(EmbeddedDocument):
name = StringField()
class Person(Document):
name = StringField()
address = StringField()
pets = ListField(EmbeddedDocumentField(Pets))
p = Person()
p.update_with_dict({
"name": "Hank",
"address": "Far away",
"pets": [
{
"name": "Scooter"
}
]
})
推荐答案
好吧,我为此做了一个函数.
Ok I just made a function for it.
您将其称为update_document(document, data_dict)
.它将循环遍历data_dict
的各项,并使用data_dict
的键获取字段实例.然后它将调用field_value(field, value)
,其中field
是字段实例. field_value()
将使用field.__class__
检查字段的类型,并基于该返回值返回MongoEngine期望的值.例如,可以直接返回普通StringField
的值,但是对于EmbeddedDocumentField
,需要创建该嵌入式文档类型的实例.它还对列表字段中的项目执行此操作.
You call it like update_document(document, data_dict)
. It will loop through the items of data_dict
and get the field instance using the key of the data_dict
. It will then call field_value(field, value)
where field
is the field instance. field_value()
will check the type of field using field.__class__
and based on that return a value that MongoEngine would expect. For example, the value of a normal StringField
can just be returned as is, but for an EmbeddedDocumentField
, an instance of that embedded document type needs to be created. It also does this trick for the items in lists fields.
from mongoengine import fields
def update_document(document, data_dict):
def field_value(field, value):
if field.__class__ in (fields.ListField, fields.SortedListField):
return [
field_value(field.field, item)
for item in value
]
if field.__class__ in (
fields.EmbeddedDocumentField,
fields.GenericEmbeddedDocumentField,
fields.ReferenceField,
fields.GenericReferenceField
):
return field.document_type(**value)
else:
return value
[setattr(
document, key,
field_value(document._fields[key], value)
) for key, value in data_dict.items()]
return document
用法:
class Pets(EmbeddedDocument):
name = StringField()
class Person(Document):
name = StringField()
address = StringField()
pets = ListField(EmbeddedDocumentField(Pets))
person = Person()
data = {
"name": "Hank",
"address": "Far away",
"pets": [
{
"name": "Scooter"
}
]
}
update_document(person, data)
这篇关于使用python dict更新MongoEngine文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!