【问题标题】:SQLAlchemy show me that "AttributeError: type object 'User' has no attribute 'columns'"SQLAlchemy 告诉我“AttributeError: type object 'User' has no attribute 'columns'”
【发布时间】:2013-08-12 08:18:12
【问题描述】:

我正在构建一个使用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'

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

【问题讨论】:

  • 为什么你在User对象上调用CreateTable?你期望会发生什么? CreateTable 需要 Table 对象,而不是声明性基础对象。
  • 嗨 Martijn Pieters,我想调用 print CreateTable(User) 因为我想查看从 SQLAlchemy 生成的创建表的 SQL 脚本,我想确认它是否是我想要的。我从 SQLAlchemy 的官方文档中学习了函数 CreateTable() 的用法。我尝试使用 CreateTable(users),但系统告诉我对象 users 不存在。
  • 那不行;你最好打开回显(在连接到数据库时传递echo=True)。

标签: python flask sqlalchemy attributes


【解决方案1】:

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

CreateTable(User.__table__)

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

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

【讨论】:

  • 我用的不是flask-SQLAlchemy,而是SQLAlchemy,因为我发现有些函数没有继承到flask-SQLAlchemy,例如:CreateTable()
猜你喜欢
  • 1970-01-01
  • 2022-12-27
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多