python - 使用 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 日志看来,它甚至没有尝试创建表。
解决方案
不确定最初的根本原因是什么,但通过遵循评论中的帮助,我能够解决问题。我将更新后的代码留在帖子中,以便遇到相同问题的其他人可以看到解决方案
推荐阅读
- python - 如何从元组列表中随机选择一个元组
- android - 自动将视频从 Android 设备复制到 PC
- arrays - 在 Rust 的数组中插入 serde_json 对象
- excel - 如何在 Excel 上选择多张图片并使用 VBA 更改它们
- spring-data-r2dbc - R2DBC 可用于 Spring boot 中的更改数据捕获?
- universal-analytics - 为什么 GA4 中的自定义事件数量比 UA 中少得多?
- javascript - 赛普拉斯 cy.request 期望抛出/失败
- vue.js - 当 v-radio 处于活动状态和禁用状态时如何初始化 radiogroup
- python - list-python 中出现次数最多的 10 个元素
- google-apps-script - Google Apps 脚本的新手 - 与 Gmail.App.sendEmail 苦苦挣扎