【发布时间】:2019-10-22 21:03:55
【问题描述】:
我是 SQLAlchemy 的新手(使用 Python 3),发现以下令人费解。在我的简单示例中,在单独的文件中定义了 2 个模型类,并通过关系链接它们。
设置是否正确?我的代码要求
Animal.pyimportOwner因为定义了关系,否则app/main.py将抛出关于Ownerclass not found 的错误。但是,official docs 和其他在线示例似乎没有导入与当前类有关系的其他类。model/__init__.py对我的情况有用吗?如果是这样,它将用于什么?看到an example that used a__init__.pyfile。
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)
【问题讨论】:
-
@AndrewAllen 每个文件有 1 个模型类有什么好处吗?
标签: python python-3.x sqlalchemy