sqlalchemy+postgresql 建表不成功换 mysql 是可以

2020-05-05 04:39:24 +08:00
 holinhot
database.py

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


SQLALCHEMY_DATABASE_URL = "postgresql+psycopg2://postgres:123@localhost/cms"
#SQLALCHEMY_DATABASE_URL = "mysql://root@localhost/cms"



engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

models.py

from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from .database import Base


class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String(15), unique=True, index=True)
hashed_password = Column(String(15))
is_active = Column(Boolean, default=True)

items = relationship("Item", back_populates="owner")


class Item(Base):
__tablename__ = "items"

id = Column(Integer, primary_key=True, index=True)
title = Column(String(15), index=True)
description = Column(String(15), index=True)
owner_id = Column(Integer, ForeignKey("users.id"))

owner = relationship("User", back_populates="items")


db.py
from sql_app import models
from sql_app.database import engine


def init_db():
models.Base.metadata.create_all(bind=engine)

init_db()
1889 次点击
所在节点    Python
4 条回复
holinhot
2020-05-05 04:40:35 +08:00
真是奇怪了,执行了很多遍我看 postgresql 里根本没有表啊,同样的代码换成 mysql 是可以建表成功
holinhot
2020-05-05 04:43:48 +08:00
结贴,navicat 的锅,不知为何在 navicat 中不管怎么刷新,还是重连都不显示 postgresql 里的表。pgAdmin 没问题
holinhot
2020-05-05 04:52:04 +08:00
zzl22100048
2020-05-05 07:58:51 +08:00
navicat 版本低了吧

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/668570

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX