gpt4 book ai didi

python - SQLAlchemy 告诉我 "AttributeError: type object ' User' 没有属性 'columns' "

转载 作者:行者123 更新时间:2023-11-30 23:34:20 24 4
gpt4 key购买 nike

我正在使用 python+Flask+SQLAlchemy 构建一个小项目,我制作了一个模型文件如下:

################# start of models.py #####################
from sqlalchemy import Column, Integer, String, Sequence, Date, DateTime, ForeignKey
from sqlalchemy.orm import relationship, backref
from dk.database import Base
import datetime

class User(Base):
__tablename__ = 'users'
id = Column(Integer, Sequence('seq_user_id'), primary_key=True)
name = Column(String(50), unique=True, index = True, nullable = False)
email = Column(String(120), unique=True, index = True, nullable = False)
password = Column(String(128), nullable = False)

def __init__(self, name, email, password):
self.name = name
self.email = email
self.password = password

def __repr__(self):
return '<User %r>' % (self.name)

class Session(Base):
__tablename__ = 'session'
id = Column(String(128), primary_key = True, nullable = False)
user_name = Column(String(30), nullable = False)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship('User', backref=backref('session', lazy='dynamic'))

def __repr__(self):
return '<Session %r>' % (self.id)
################# end of models.py #####################

我构建了一个初始文件:

################# start of __init__.py #################
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config') #load database config information
db = SQLAlchemy(app)
################# end of __init__.py #################

当我在脚本中运行“init_db()”时,构建数据库的表成功。但是当我想查看 SQL 脚本然后我在脚本中运行“print CreateTable(User)”时,系统显示以下错误:

  File "/home/jacky/flaskcode/venv/lib/python2.6/site-packages/sqlalchemy/schema.py", line 3361, in __init__
for column in element.columns
AttributeError: type object 'User' has no attribute 'columns'

我不知道如何解决这个问题!

最佳答案

您需要为CreateTable()传入一个Table对象:

CreateTable(User.__table__)

但是如果您想查看 SQLAlchemy 发出的 SQL 语句,最好通过设置 echo=True when creating the connection 来打开回显。 .

Flask SQLAlchemy 集成层支持SQLALCHEMY_ECHO option设置该标志。

关于python - SQLAlchemy 告诉我 "AttributeError: type object ' User' 没有属性 'columns' ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18182319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com