SQLAlchemy show me that "AttributeError: type object 'User' has no attribute 'columns'"


Question

I am building a small project use python+Flask+SQLAlchemy, I make a model file following:

################# 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 #####################

and I build a initial file following:

################# 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 #################

when I run the "init_db()" in script, tables built to database successful. but when I want to see the SQL script then I run the "print CreateTable(User)" in script, the system show follwing errors:

  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'

I have no idea how to solve this problem!

1
1
3/16/2017 4:56:17 PM

Accepted Answer

You need to pass in a Table object for CreateTable():

CreateTable(User.__table__)

but if you wanted to see the SQL statements that SQLAlchemy issues you are better off switching on echoing by setting echo=True when creating the connection.

The Flask SQLAlchemy integration layer supports a SQLALCHEMY_ECHO option to set that flag.

3
8/12/2013 8:41:37 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon