正在导入用于关系的SQLAlchemy模型?

问题描述 投票:1回答:1

我是SQLAlchemy的新手(使用Python 3),发现以下令人困惑的地方。在我的简单示例中,在单独的文件中定义了2个模型类,它们之间具有关联关系。

  1. 设置正确吗?我的代码要求Animal.py导入Owner,因为已定义了关系,否则app/main.py将引发有关未找到Owner类的错误。但是,official docs和其他在线示例似乎并未导入当前类所关联的其他类。

  2. 具有model/__init__.py对我的情况有用吗?如果是这样,它将用于什么用途?看到an example that used a __init__.py file

Github存储库__init__.py

文件结构

https://github.com/nyxynyx/sqlalchemy-class-import-error

app / main.py

enter image description here

models / foo / Animal.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 / Owner.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')

lib / db.py

from sqlalchemy import *
from ..Base import Base

class Owner(Base):
    __tablename__ = 'owners'
    id = Column(Integer, primary_key=True)
    name = Column(Text)
python python-3.x sqlalchemy
1个回答
2
投票

the Animal.py很好。问题是,如果从不导入owner.py,则sqlalchemy永远不会看到Owner模型/表,因此它永远不会将其注册到Base元数据中。您可以通过

将Owner的进口从animal.py删除到main.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)

在保留单独的模型文件的同时查看它的工作。

© www.soinside.com 2019 - 2024. All rights reserved.