如何在sqlalchemy的before_insert事件上添加模型的关系实例?

时间:2019-03-07 18:28:39

标签: flask sqlalchemy flask-sqlalchemy

我想在创建模型关系的实例时添加模型关系的实例。

尽管 before_insert sqlalchemy事件允许设置简单属性,但它似乎不适用于关系。

是否可以通过此事件执行此操作?实现该目标的标准方法是什么?

audio_project_rel = db.Table(
    'audio_project_rel',
    db.Column('project_id', db.Integer, db.ForeignKey('project.id'), primary_key=True),
    db.Column('audio_id', db.Integer, db.ForeignKey('audio.id'), primary_key=True)
)

class Audio(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    path = db.Column(db.String, unique=True, nullable=False)

class Project(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, unique=True, nullable=False)
    audiolist_filename = db.Column(db.String, nullable=False)
    audios = db.relationship('Audio',
            secondary=audio_project_rel,
            lazy=True,
            backref=db.backref('projects', lazy=True))

@event.listens_for(Project, 'before_insert')
def get_audiolist_from_file(mapper, connection, project):    
    with open(project.audiolist_filename, 'r') as audiolist_file:
        for line in audiolist_file:
            _path = line.strip()
            audio = Audio.query.filter(Audio.path==_path).first()
            if not audio:
                audio = Audio()
                audio.path = _path 
            project.audios.append(audio) # not added
        project.name = 'somename' # added