【问题标题】:sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: user.wordssqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL 约束失败:user.words
【发布时间】:2021-08-07 06:37:47
【问题描述】:

我查看了其他具有相同标题的帖子,但它们并没有解决我的问题。上面标题中的错误消息就是我得到的。 我为数据库制作了一个简单的数据库和构造函数。只是为了测试,我正在尝试将单词“hello”添加到 User 类中的“words”列中。但我不断收到这个错误。我已经尝试将自动增量放在类列中,但我最终得到了另一个错误。出了什么问题?请看下面的代码。 Python 和 Flask。

from flask import Flask, request, redirect, url_for, render_template
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
import sqlite3

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE URI"] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'user'
    words = db.Column(db.String(200), primary_key=True)
    
    def __init__(self, thewords):
        self.thewords = thewords

db.create_all()
db.session.commit()

texts = "hello"
textstuffent = User(texts)
db.session.add(textstuffent)
db.session.commit()

results = User.query.all()
print(results)

@app.route('/', methods = ['POST', 'GET'])
def hello():
    return render_template('Textarea.html')

app.run(debug=True)

【问题讨论】:

  • 在您的User 类中,您设置了self.thewords,但您从未设置words,这是实际的数据库列。
  • @John Gordon 等等,“单词”列必须在 init 中设置?

标签: python database flask sqlalchemy


【解决方案1】:

对于以后访问此页面的任何人,我都发现了问题所在。我没有将“单词”称为“self.words”。我的代码现在可以工作了,我终于可以继续编码了,这样以后其他一些错误可能会让我感到困惑。请看下文。您可以在 User 类中看到代码的差异。我使用 query.all() 来证明数据已经进入数据库。

from flask import Flask, request, redirect, url_for, render_template
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
import sqlite3

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE URI"] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class User(db.Model):    
    words = db.Column(db.String(200), primary_key=True, nullable=False)

    def __init__(self, thewords):
        self.words = thewords

db.create_all()
db.session.commit()

texts = "hello"
textstuffent = User(texts)
db.session.add(textstuffent)
db.session.commit()

print(User.query.all())

@app.route('/', methods = ['POST', 'GET'])
def hello():
    return render_template('Textarea.html')
        
app.run(debug=True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-10
    • 2021-07-02
    • 2021-06-29
    • 2021-06-12
    • 1970-01-01
    • 2023-03-20
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多