【问题标题】:Using SQLAlchemy as an ORM for python - relation doesn't exist使用 SQLAlchemy 作为 Python 的 ORM - 关系不存在
【发布时间】:2019-08-12 10:25:58
【问题描述】:

我在 Python 中遇到了 sqlalchemy 的问题。

我有以下文件:

base.py:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres:mysecretpassword@localhost:5432/postgres',echo=True)
Base = declarative_base(engine)

产品.py:

from sqlalchemy import Table,Date,TEXT,Column,BIGINT,Integer,Boolean
from base import Base    

class Product(Base):

    __tablename__ = 'products'
    id = Column('id',BIGINT, primary_key=True)
    barcode = Column('barcode' ,BIGINT)
    productName = Column('name', TEXT)
    productType = Column('type', Integer)
    maufactureName=Column('maufacture_name',TEXT,nullable=True)
    manufactureCountry = Column('manufacture_country', TEXT)
    manufacturerItemDescription = Column('manufacture_description',TEXT)
    unitQuantity=Column('uniq_quantity',Integer)
    quantity=Column('quantity',Integer)
    quanityInPackage=Column('quantity_in_package',Integer)
    isWeighted=Column('is_weighted',Integer)
    picture=Column('picture_url',TEXT)


    def __init__(self,args...):
   .....

main.py:

from Product import Product
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from base import Base
Base.metadata.create_all()
Session = sessionmaker()
session=Session()
session.add(Product(...))
session.commit()

当我运行 main 时,我不断收到产品关系不存在的错误:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "products" does not exist

知道为什么吗?从 sqlalchemy 日志来看,它似乎甚至没有尝试创建表。

【问题讨论】:

  • 不知道 repository 是什么,但是当您将该 Base 作为参数添加到您的类时,您将该模型/类 映射 到特定表你的数据库。请提供您的模型,以便我们找出未创建您的表的原因。如果所有类都是同一个基类的子类(并且它们绑定到同一个 db_engine),则不同的文件不会影响创建。
  • 存储库是指我们在 java 中为每个 DAO 类创建的 JPA 存储库。我在课堂上添加了 sqlalchemy 部分
  • 正如我所说,你不应该有它,对象关系映射器是那个类的“所有者”,你不能弄乱它的内部,你可以扩展它的方法或者。您应该遵循一些教程或官方文档并删除所有代码。只有当你做对了,你才能添加一些可能工作的东西。
  • 关键是用declarative_base(engine) 调用将引擎绑定到基础。将该文件从 Base.py 重命名为 base.py(没有 .py 文件名应该包含大写字母),并在其中创建引擎和 Base,并将其导入 main.py。而且您不需要在 create_all 调用中传递引擎。
  • 现在它可以工作了,我更新了评论中的代码,以便它可以帮助其他人。谢谢你@ipaleka

标签: python sqlalchemy


【解决方案1】:

不确定最初的根本原因是什么,但通过 cmets 中的帮助,我能够解决问题。我将更新后的代码留在帖子中,以便遇到相同问题的其他人可以看到解决方案

【讨论】:

    猜你喜欢
    • 2018-10-04
    • 2021-09-18
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 2020-05-16
    相关资源
    最近更新 更多