问题
I want delcare my models before make connection with database (for some reason like multi-threading, and dynamic load of database config uri).
Documentation say to use like that:
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=''))
We can see what model declaration need session
(in __mongometa__
). How can i declare WikiPage model without session
variable ? And set it later ?
回答1:
Solution can be declare model without __mongometa__
:
class WikiPage(MappedClass):
_id = FieldProperty(schema.ObjectId)
title = FieldProperty(schema.String(required=True))
text = FieldProperty(schema.String(if_missing=''))
Then make make mapping manually with a collection:
session = ODMSession(bind=create_datastore(uri))
collection_ = collection('wiki_page', session)
session.mapper(WikiPage, collection_)
来源:https://stackoverflow.com/questions/41807329/declare-model-before-create-connection-in-ming