簡體   English   中英

SQLAlchemy告訴我“AttributeError:type object'User'沒有屬性'columns'”

[英]SQLAlchemy show me that “AttributeError: type object 'User' has no attribute 'columns'”

我正在使用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啟用回顯。

Flask SQLAlchemy集成層支持SQLALCHEMY_ECHO選項來設置該標志。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM