在创建连接之前声明模型

2024-09-27 07:30:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望在与数据库建立连接之前先关心我的模型(出于某些原因,比如多线程和数据库配置uri的动态加载)。你知道吗

文件说明如下:

from ming import create_datastore
from ming.odm import ThreadLocalODMSession
from ming import schema
from ming.odm import FieldProperty
from ming.odm.declarative import MappedClass

session = ThreadLocalODMSession(
    bind=create_datastore('odm_welcome')
)

class WikiPage(MappedClass):
    class __mongometa__:
        session = session
        name = 'wiki_page'

    _id = FieldProperty(schema.ObjectId)
    title = FieldProperty(schema.String(required=True))
    text = FieldProperty(schema.String(if_missing=''))

我们可以看到模型声明需要什么session(在__mongometa__)。如何声明没有session变量的WikiPage模型?以后再定?你知道吗


Tags: from模型import数据库sessionschemacreateclass
1条回答
网友
1楼 · 发布于 2024-09-27 07:30:20

解决方案可以在没有__mongometa__的情况下声明模型:

class WikiPage(MappedClass):
    _id = FieldProperty(schema.ObjectId)
    title = FieldProperty(schema.String(required=True))
    text = FieldProperty(schema.String(if_missing=''))

然后使用集合手动进行映射:

session = ODMSession(bind=create_datastore(uri))
collection_ = collection('wiki_page', session)
session.mapper(WikiPage, collection_)

相关问题 更多 >

    热门问题