首页 > 解决方案 > 使用 SQLAlchemy 作为 Python 的 ORM - 关系不存在

问题描述

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

我有以下文件:

基础.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...):
   .....

主要.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 日志看来,它甚至没有尝试创建表。

标签: pythonsqlalchemy

解决方案


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


推荐阅读