首页 > 解决方案 > AttributeError:“SQLAlchemy”对象没有属性“整数”

问题描述

当我运行我的 .py 代码时,它会引发错误“AttributeError:'SQLAlchemy' 对象没有属性'integer'”并且代码中的'db' 出现红线。第 14 行抛出错误。

from datetime import datetime
from flask import Flask, render_template, url_for,flash,redirect
from flask_sqlalchemy import SQLAlchemy
from forms import RegistrationForm, LoginForm

app = Flask(__name__)    #name of the module
app.config['SECRET_KEY']= 'b2ffa54db1c495dab1f21973b39c400a'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db =  SQLAlchemy(app)


class User(db.Model):
    id = db.column(db.integer, primary_key=True)
    username = db.column(db.string(25), unique=True, 
nullable=False)
    email = db.column(db.string(100), unique=True, nullable=False)
    password = db.column(db.string(100), unique=True, 
nullable=False)
    image_file = db.column(db.string(20), nullable=False, 
default='default.jpg')
    posts = db.relationship('Post', backreff='author', lazy=True)


    def __repr__(self):
       return f"user('{self.username}','{self.email}', '{self.image_file}')"

class Post(db.Model):
    id = db.column(db.integer, primary_key=True)
    title = db.column(db.String(120), nullable=False)
    date_posted = db.column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.column(db.Text, nullable=False)

def __repr__(self):
       return f"post('{self.title}','{self.date_posted}')"

标签: python-3.x

解决方案


您需要将第一个字母大写:

id = db.column(db.Integer, primary_key=True)

这应该适合你。请注意,您必须对您定义的所有数据类型执行此操作,否则它将为所有数据类型抛出AttributeError

from datetime import datetime
from flask import Flask, render_template, url_for,flash,redirect
from flask_sqlalchemy import SQLAlchemy
from forms import RegistrationForm, LoginForm

app = Flask(__name__)    #name of the module
app.config['SECRET_KEY']= 'b2ffa54db1c495dab1f21973b39c400a'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db =  SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(25), unique=True, 
nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)
    password = db.Column(db.String(100), unique=True, 
nullable=False)
    image_file = db.Column(db.String(20), nullable=False, 
default='default.jpg')
    posts = db.relationship('Post', backreff='author', lazy=True)


    def __repr__(self):
       return f"user('{self.username}','{self.email}', '{self.image_file}')"

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)

def __repr__(self):
       return f"post('{self.title}','{self.date_posted}')"

推荐阅读