Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQLAlchemy连接表_Python_Sqlalchemy - Fatal编程技术网

Python SQLAlchemy连接表

Python SQLAlchemy连接表,python,sqlalchemy,Python,Sqlalchemy,我试图存储用户每次执行某些操作时的历史信息。由于多个表的历史信息是相同的(例如存储从文件x导入的数据),我希望将历史数据保存在单独的表中,并将相关历史项目的id存储在其他表中。我遇到的问题是,并非每个表在每次历史记录更改时都会将其历史记录列表添加到历史记录中,因此为历史记录中的每个表(数十个表)存储ForeignKey看起来不是正确的方法 from sqlalchemy.ext.declarative import declared_attr from sqlalchemy import Dat

我试图存储用户每次执行某些操作时的历史信息。由于多个表的历史信息是相同的(例如存储从文件x导入的数据),我希望将历史数据保存在单独的表中,并将相关历史项目的id存储在其他表中。我遇到的问题是,并非每个表在每次历史记录更改时都会将其历史记录列表添加到历史记录中,因此为历史记录中的每个表(数十个表)存储ForeignKey看起来不是正确的方法

from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import DateTime, Column, Integer, String
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from sqlalchemy.sql.schema import ForeignKey

class TableA(Base):
    __tablename__ = 'tablea'

    id = Column(Integer, primary_key=True, nullable = False)
    data = Column(String(), nullable=True)
    history = relationship("History")

class TableB(Base):
    __tablename__ = 'tableb'

    id = Column(Integer, primary_key=True, nullable = False)
    data = Column(String(), nullable=True)
    history = relationship("History")

class TableC(Base):
    __tablename__ = 'tablec'

    id = Column(Integer, primary_key=True, nullable = False)
    data = Column(String(), nullable=True)
    history = relationship("History")

class History(Base):
    __tablename__ = 'history'

    id = Column(Integer, primary_key=True, nullable = False)
    details = Column(String(), nullable=True)
    version = Column(String(), nullable=True)
    tablea_id = Column(Integer, ForeignKey('tablea.id'))
    tableb_id = Column(Integer, ForeignKey('tableb.id'))
    tablec_id = Column(Integer, ForeignKey('tablec.id'))

class Base(object):

    @declared_attr
    def __tablename__(cls):
        return str(cls.__name__)
    create_date = Column(DateTime, default=func.now()) 

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base(cls=Base)

我能解决这个问题的唯一方法是将每个表a、B、C中的历史id列表作为字符串存储。然后使用JSON将字符串解码为python列表。但这种方法既单调又容易出错。有什么想法吗?

有更好的方法,请阅读示例。特别是,或者一个例子应该适合您的要求。@van谢谢。我准确地复制了鉴别器示例,用历史记录代替地址。我的案例有点不同,因为与唯一地址不同,历史对象完全相同,但被多个表引用。此外,我希望附加到历史“列表”中,而不是像示例中那样一次性编写所有内容。我创建了历史记录以便可以在多个表中存储引用,但是tablea.histories=[self.history]session.add(tablea)不允许我追加。我将介绍泛型_fk,但事件侦听器看起来有点奇怪。