简体   繁体   English

SQLAlchemy:NoForeignKeysError

[英]SQLAlchemy: NoForeignKeysError

I'm creating two tables and linking them using SQLAlchemy relationships (using SQLite as my DB) 我正在创建两个表并使用SQLAlchemy关系链接它们(使用SQLite作为我的数据库)

class Album(Base):
    __tablename__ = 'albums'
    id = Column(INTEGER, primary_key=True, unique=True, autoincrement=True, nullable=False)
    name = Column(TEXT)
    tracks = relationship('Track', back_populates='albums')

class Track(Base):
    __tablename__ = 'tracks'
    id = Column(INTEGER, primary_key=True, unique=True, autoincrement=True, nullable=False)
    name = Column(TEXT)
    albums = relationship('Album', back_populates='tracks')

def insert_data(metadata, path, ext):
    session = get_session() # returns SQLAlchemy session
    tracks = get_or_create(session,
                           Track,
                           name=metadata['title']
                           )
    _ = get_or_create(session,
                      Album,
                      name=metadata['album'],
                      tracks=tracks
                      )


def get_instance(session, model, permutation):
    try:
        return session.query(model).filter_by(**permutation).first()
    except NoResultFound:
        return None


def create_instance(session, model, permutation):
    try:
        instance = model(**permutation)
        session.add(instance)
        session.flush()
    except Exception as msg:
        log.error(f'model:{model}, args:{permutation} -> msg:{msg}')
        session.rollback()
        raise msg
    return instance


def get_or_create(session, model, **metadata):
    data_permutations = [dict(zip(metadata, value)) for value in product(*metadata.values())]
    ret = []
    for permutation in data_permutations:
        instance = get_instance(session, model, permutation)
        if instance is None:
            instance = create_instance(session, model, permutation)
        ret.append(instance)
    session.commit()
    return ret

insert_metadata(metadata, path, ext)

metadata looks like this: 元数据看起来像这样:

{
 'name': ['foo'],
 'data': ['bar', 'baz'],
 ...
}

It can have an unlimited amount of keys, that can have lists of any length as values. 它可以具有无限量的密钥,可以具有任何长度的列表作为值。 Therefore I create all possible outcomes (permutations) of this data and save it as a list of unique dicts, like this: 因此,我创建了这些数据的所有可能结果(排列),并将其保存为唯一的dicts列表,如下所示:

[{'name': 'foo', 'data': 'bar'}, {'name': 'foo', 'data': 'baz'}]

Now, when I call insert_data, I'm getting the following message: 现在,当我调用insert_data时,我收到以下消息:

sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'albums' and 'tracks'.

Traceback shows that the function that's throwing the exception is get_instance. Traceback显示抛出异常的函数是get_instance。 I'm suspecting it has something to do with my query, since I double-checked table creation against both the documentation and other Stack Overflow questions, and the syntax seems to be correct. 我怀疑它与我的查询有关,因为我根据文档和其他Stack Overflow问题仔细检查了表创建,并且语法似乎是正确的。

How do I need to alter my query (see the try block in get_instance) so the program doesn't crash? 我如何需要更改我的查询(请参阅get_instance中的try块)以便程序不会崩溃? Or is the error elsewhere? 或者其他地方的错误?

问题是表'tracks'缺少列album_id:

    album_id = Column(INTEGER, ForeignKey('albums.id'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM