我定义了这样的模型:
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
first = db.Column(db.String(64))
last = db.Column(db.String(64))
dob = db.Column(db.Date)
street_addr1 = db.Column(db.String(64))
street_addr2 = db.Column(db.String(64))
city = db.Column(db.String(64))
state = db.Column(db.String(2))
zip = db.Column(db.String(9))
gender = db.Column(db.Enum('M', 'F'))
home_box = db.Column(db.String(32))
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return '<User %r>' % self.username
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
views.py:
@main.route('/', methods=['GET', 'POST'])
def index():
form = RegistrationForm()
if form.validate_on_submit():
user = User()
user.username = form.username.data
user.first = form.first_name.data
user.last = form.last_name.data
user.city = form.city.data
user.dob = form.dob.data
user.gender = form.gender.data
user.home_box = form.home_box.data
user.state = form.state.data
user.street_addr1 = form.street_addr1.data
user.street_addr2 = form.street_addr2.data
user.zip = form.zip.data
user.password = form.password.data
db.session.add(user)
db.session.commit
目前,插入失败,因为未设置id:
sqlalchemy.exc.IntegrityError: (IntegrityError) constraint failed 'INSERT INTO users (first, last, dob, street_addr1, street_addr2, city, state, zip, gender, home_box, username, password_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' ('Nate', 'Reed', '1980-11-11', '', '', '', '', '', 'male', '', 'natereed', 'pbkdf2:sha1:1000$N8JHXEDU$24a7724ae9edda81a73e6b92d23aa576ad8284aa')
如何进行id自动增量?我的理解是它必须在表(而不是列)级别完成。我如何在上面的代码中执行此操作?
答案 0 :(得分:2)
我发现问题是我试图插入无效的性别值。这是一个有价值观的词汇&#39; M&#39;或者&#39; F&#39;。
如果表单可以从模型生成,那将是很好的,因为这将消除此错误的可能性。关于使用Flask进行此操作的任何指示?