pony orm在创建数据库之前定义实体子类 我正在创建一个包含bot类的库。我希望它能够在小马ORM的帮助下将消息日志和其他一些信息存储在SQL数据库中。想法是让机器人接受...

问题描述 投票:0回答:0

from pony import orm class Message(orm.Entity): text = orm.Required(unicode) class Database(orm.Database): def __init__(self, path): # super(..).__init__(..) # bind Message to self class Bot(object): def __init__(self, path): self.database = Database(path)

现在,如果我可以从数据库继承。

任何想法?也许我可以用Sqlalchemy等另一个ORM来实现这一目标?

您可以尝试以下模式:

from pony import orm def entities_for_db(db: orm.Database): """ Creates set of entities connected to a specified database. :param db: database to which entities should be connected. :return: class with database entities. """ class Entities: class Language(db.Entity): name = orm.Required(str, max_len=128) symbol = orm.Required(str, max_len=32) @classmethod def get_by_symbol(cls, symbol): return cls.select(lambda l: l.symbol == symbol).first() @classmethod def get_or_create(cls, symbol, name): return cls.select(lambda l: l.symbol == symbol and l.name == name).first() \ or cls(symbol=symbol, name=name) def to_dict(self): return dict(name=self.name, symbol=self.symbol) return Entities # First sequence run for 2 different databases db1 = orm.Database(provider='sqlite', filename="test1.sqlite", create_db=True) db2 = orm.Database(provider='sqlite', filename="test2.sqlite", create_db=True) db1_entities = entities_for_db(db1) db2_entities = entities_for_db(db2) db1.generate_mapping(create_tables=True) db2.generate_mapping(create_tables=True) with orm.db_session(): result1 = db1_entities.Language.get_or_create("en", "English") result2 = db2_entities.Language.get_or_create("pl", "Polish") # Disconnect to let the sequence be run once again db1.disconnect() db2.disconnect() # Second sequence run for the same databases db1 = orm.Database(provider='sqlite', filename="test1.sqlite", create_db=True) db2 = orm.Database(provider='sqlite', filename="test2.sqlite", create_db=True) db1_entities = entities_for_db(db1) db2_entities = entities_for_db(db2) db1.generate_mapping(create_tables=True) db2.generate_mapping(create_tables=True) with orm.db_session(): db1_entities.Language.get_or_create("de", "German") db2_entities.Language.get_or_create("fr", "French")
    

python inheritance orm ponyorm
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.