使用pymodm from_document构建mongo doc

时间:2017-11-23 12:21:18

标签: mongodb python-3.x pymodm

我正在尝试使用from_document api从python字典构造pymodm文档。我收到错误" ValueError:无法识别的字段名称' prim_key'"

以下是我用最少的代码编写的示例代码。

from pymodm import connect, EmbeddedMongoModel, MongoModel, fields
from pymodm.errors import ValidationError, ConfigurationError
from pymongo.write_concern import WriteConcern
import pprint
from datetime import datetime

class sample_doc(MongoModel):
    prim_key = fields.CharField(primary_key=True)
    another_field = fields.CharField()

    class Meta:
        write_concern = WriteConcern(j=True)
        connection_alias = 'pymodm-tester'

connect("mongodb://localhost:27017/pymodm-tester", alias="pymodm-tester")

q = {'prim_key' : 'prim_val', "another_field" : "another_filed1" }
sample_doc.from_document(q).save()

1 个答案:

答案 0 :(得分:0)

docs

  

document:描述MongoDB文档的Python字典。按键   必须根据每个模型字段命名文档   mongo_name属性,而不是字段的Python名称。

看起来,为了在尝试时实例化模型,需要指定mongo_name字段。这对你有用:

class sample_doc(MongoModel):
    prim_key = fields.CharField(primary_key=True, mongo_name="prim_key")
    another_field = fields.CharField(mongo_name="another_field")

    class Meta:
        write_concern = WriteConcern(j=True)
        connection_alias = 'pymodm-tester'