python - 导入关系中使用的 SQLAlchemy 模型?

标签 python python-3.x sqlalchemy

我是 SQLAlchemy 的新手(使用 Python 3),并发现以下令人困惑的地方。在我的简单示例中,在单独的文件中定义了 2 个模型类,并通过关系将它们链接起来。

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

  2. model/__init__.py 对我的案例有用吗?如果有的话,它会用来做什么?看到了an example that used a __init__.py file

Github 存储库:https://github.com/nyxynyx/sqlalchemy-class-import-error

文件结构

enter image description here

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/

相关文章:

python - 如何找到 SQLAlchemy 模型的所有混合属性?

python - gspread import_csv file_id 参数是什么?

python - 用零填充 3D 列表中的缺失值以创建 3D numpy 数组

python - 使用 python 在 Elasticsearch 中批量部分更新插入

python - Django-使用内联函数时进程中止

python - 如何将记录从一张表转移到另一张表?

python - 反向传播:为什么乘以 sigmoid 的导数时误差不趋近于零?

Python,通过比较不同字段来比较字典列表的差异

python - 在检查长度时添加两个列表

python - 从 SQLAlchemy 中的时间戳中选择日期