簡體   English   中英

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL 約束失敗:user.words

[英]sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: user.words

我已經查看了具有相同標題的其他帖子,但它們並沒有解決我的問題。 上面標題中的錯誤消息就是我得到的。 我為數據庫制作了一個簡單的數據庫和構造函數。 只是為了測試,我正在嘗試將單詞“hello”添加到 class 用戶的“單詞”列中。 但我不斷收到這個錯誤。 我已經嘗試將自動增量放在 class 列中,但我最終得到了另一個錯誤。 出了什么問題? 請看下面的代碼。 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)

對於將來訪問此頁面的任何人,我都發現了問題所在。 我沒有將“單詞”稱為“self.words”。 我的代碼現在可以正常工作了,我終於可以繼續編碼,讓我松了一口氣,這樣其他一些錯誤可以讓我在以后的道路上感到困惑。 請看下文。 您可以在用戶 class 中看到代碼的差異。 我使用 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)

暫無
暫無

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

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