python - NOT NULL 约束失败但字段不为空

标签 python python-2.7 sqlalchemy

我正在尝试使用我的 Web 表单添加新项目。

但是我得到了这个错误。电子邮件不为空,但我从打印声明中验证了这一点。

在这一行

File "/Users/j/udacity/item_catalog/item-catalog-190/application.py", line 131, in newItem
    session.commit()


IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: category.email [SQL: u'INSERT INTO category (name, email) VALUES (?, ?)'] [parameters: (u'Pilates', None)]


@app.route('/catalog/new', methods=['GET','POST'])
def newItem():
    if request.method == 'POST':
        placeholder=request.form['category']
        category = Category(name=placeholder)
        print "**********", login_session['email']
        email = login_session['email']
        newThing = Item(name=request.form['name'], description=request.form['description'], price=request.form['price'],category=category, email=email)
        session.add(newThing)
        session.commit()
        return redirect('/catalog')
    else:
        return render_template('newitem.html')

这是我的两个表。

class Item(Base):
__tablename__ = 'item'

name = Column(String(80), nullable=False)
id = Column(Integer, primary_key=True)
description = Column(String(250))
price = Column(String(8))
category_id = Column(Integer, ForeignKey('category.id'))
email = Column(String(250),nullable=False)
category = relationship(Category)


class Category(Base):
__tablename__ = 'category'

id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
email = Column(String(250), nullable=False)

最佳答案

您的 category 表要求 email 字段为 NOT NULL,并且当您创建新类别时:

category = Category(name=placeholder)

email 字段的默认值为 NULL

这是对 INSERT 的查询:

SQL: u'INSERT INTO category (name, email) VALUES (?, ?)'] [parameters: (u'Pilates', None)

如您所见,第二个参数(即 email)为 None(在 SQL 中转换为 null

您可能想将代码更改为:

if request.method == 'POST':
    placeholder=request.form['category']
    email = login_session['email'] # moved the email here
    print "**********", login_session['email']
    category = Category(name=placeholder, email=email) # here you have the email variable so you can use it

关于python - NOT NULL 约束失败但字段不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40943464/

相关文章:

python - 如何通过互联网在两台计算机之间建立 UDP 连接

python - 运行 pyinstaller 时出错(1920、 'LoadLibraryEx'、 'System cannot access the file')

python - Flutter 与 Python Django RESTFUL API

python-2.7 - 在 Python 中将 str 消息插入 Unicode 日志模板时出现 UnicodeDecodeError

python - 如何按大小写降序排列?

Python 列表理解 : set all elements in an array to 0 or 1

python - 检查与另一个列表匹配的嵌套列表值组合

python - tkinter 文本小部件中的撤消功能

python - 如何使用sqlalchemy orm实现子选择?

python - SQLAlchemy 中与过滤器的自引用关系