该应用程序具有这样的逻辑:将人员列表存储在数据库中,每个人都有一个实时计算的评分,并且该值永远不会存储在数据库中。我想使用一个类来处理数据库字段:姓名、年龄等和非数据库字段:评级。
在 sqlalchemy 中可以吗?现在我正在使用继承 Man -> ManMapping:
class Man:
rating = None
def get_rating(self):
return self.rating
...
class ManMapping(Base, Man):
__tablename__ = 'man'
id = Column('man_id', Integer, primary_key=True)
name = Column(Unicode)
...
它有效,但对我来说看起来很糟糕。这是正确的方法还是我必须做其他事情?
最佳答案
这是正确的解决方案:https://docs.sqlalchemy.org/en/13/orm/constructors.html 混合属性在某种程度上不如这个灵活。接受的答案不是问题的实际答案。
The SQLAlchemy ORM does not call init when recreating objects from database rows. The ORM’s process is somewhat akin to the Python standard library’s pickle module, invoking the low level new method and then quietly restoring attributes directly on the instance rather than calling init.
If you need to do some setup on database-loaded instances before they’re ready to use, there is an event hook known as InstanceEvents.load() which can achieve this; it is also available via a class-specific decorator called reconstructor(). When using reconstructor(), the mapper will invoke the decorated method with no arguments every time it loads or reconstructs an instance of the class. This is useful for recreating transient properties that are normally assigned in init:
from sqlalchemy import orm
class MyMappedClass(object):
def __init__(self, data):
self.data = data
# we need stuff on all instances, but not in the database.
self.stuff = []
@orm.reconstructor
def init_on_load(self):
self.stuff = []
关于python - 添加到 sqlalchemy 映射类非数据库属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44270338/