python - 添加到 sqlalchemy 映射类非数据库属性

标签 python sqlalchemy

该应用程序具有这样的逻辑:将人员列表存储在数据库中,每个人都有一个实时计算的评分,并且该值永远不会存储在数据库中。我想使用一个类来处理数据库字段:姓名、年龄等和非数据库字段:评级。

在 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/

相关文章:

Python ThreadPoolExecutor 线程未完成

python - 使用列表作为列中的数据类型(SQLAlchemy)

python - 尝试设置多对多关联对象时 backref 上的关键错误

python - 如何使用循环从 Pandas 数据框中获取值?

python - 在 python 日志记录中使用 dictConfig,需要使用与 dict 中定义的文件不同的文件创建记录器。

python - 我正在尝试创建一个 cal_average 函数,但是我不断收到 python 无法分配给函数调用的语法错误

python - SQLAlchemy 中的数据库列表

python - 在 SQLAlchemy 中插入带有外键的对象的正确方法是什么?

python - 我在尝试查找词频时收到 TypeError : unhashable type: 'list' ,

python - 如何在没有数据重复的情况下将 pandas 数据框插入数据库?