python-3.x - 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}')"
解决方案
您需要将第一个字母大写:
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}')"
推荐阅读
- autodesk-forge - 通过设计自动化进行 Dwg 比较
- reactjs - 使用 onKeyDown 聚焦下一个元素
- node.js - 节点 js、socket.io、redis 和 pm2
- java - Java LocalDateTime minusYears 表示浮动年数
- python - scipy(python)中的高效3D插值/近似
- azure-iot-hub - IOT-HUB 设备 node.js sdk message.on 方法不起作用
- azure - 扩展开发人员在 Azure Api 管理上的注册
- c# - WPF GridSplitter 不工作
- chatbot - 如何在 DialogFlow v2 中发送额外数据?
- algorithm - 绘制特定图形的算法