我是 SQLAlchemy 的新手(使用 Python 3),并发现以下令人困惑的地方。在我的简单示例中,在单独的文件中定义了 2 个模型类,并通过关系将它们链接起来。
设置正确吗?我的代码要求
Animal.py
importOwner
因为定义了关系,否则app/main.py
将抛出有关Owner
类未找到的错误。但是,official docs 和其他在线示例似乎没有导入与当前类有关系的其他类。model/__init__.py
对我的案例有用吗?如果有的话,它会用来做什么?看到了an example that used a__init__.py
file。
Github 存储库:https://github.com/nyxynyx/sqlalchemy-class-import-error
文件结构
app/main.py
import sys
sys.path.append('..')
from lib.db import db_session
from models.foo.Animal import Animal
if __name__ == '__main__':
print(Animal.query.all())
models/foo/Animal.py
from sqlalchemy import *
from sqlalchemy.orm import relationship
from ..Base import Base
from .Owner import Owner <-------------- !!!!! if not imported, error occurs when running main.py !!!!!
class Animal(Base):
__tablename__ = 'animals'
id = Column(Integer, primary_key=True)
name = Column(Text)
owner_id = Column(Integer, ForeignKey('owners.id'))
owner = relationship('Owner')
models/Foo/Owner.py
from sqlalchemy import *
from ..Base import Base
class Owner(Base):
__tablename__ = 'owners'
id = Column(Integer, primary_key=True)
name = Column(Text)
lib/db.py
import json
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy import create_engine
with open('../settings.json') as f:
settings = json.load(f)
user, password, host, port, dbname = settings['db']['user'], settings['db']['password'], settings['db']['host'], settings['db']['port'], settings['db']['dbname']
connection_url = f'postgresql://{user}:{password}@{host}:{port}/{dbname}'
engine = create_engine(connection_url)
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db_session = scoped_session(Session)
最佳答案
animal.py 没问题。问题是,如果 Owner.py 从未导入,则 sqlalchemy 永远不会看到所有者模型/表,因此它永远不会将其注册到基础元数据中。您可以将 Owner 从 Animal.py 中删除到 main.py 中,如下所示
import models.foo.Owner
在保留单独的模型文件的同时查看它的工作原理。
关于python - 导入关系中使用的 SQLAlchemy 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58512291/