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

Joh*_*ohn 3 python sqlalchemy python-2.7

我正在尝试使用我的网络表单添加新项目.

但是我得到了这个错误.虽然我从打印声明中验证了该电子邮件,但该电子邮件不为空.

在这条线上

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')
Run Code Online (Sandbox Code Playgroud)

这是我的两张桌子.

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)
Run Code Online (Sandbox Code Playgroud)

Dek*_*kel 5

您的category表需要该email字段NOT NULL,并在您创建新类别时:

category = Category(name=placeholder)
Run Code Online (Sandbox Code Playgroud)

email字段的默认值为NULL.

这是查询INSERT:

SQL: u'INSERT INTO category (name, email) VALUES (?, ?)'] [parameters: (u'Pilates', None)
Run Code Online (Sandbox Code Playgroud)

如您所见,第二个参数(即email)是None(转换为nullSQL.

您可能希望将代码更改为:

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
Run Code Online (Sandbox Code Playgroud)