我有一个sqlalchemy模型和一个向表中添加一些元素的方法。这是模型和功能:
class Roles(alchemyDB.Model):
__tablename__ = 'roles'
id = alchemyDB.Column(alchemyDB.Integer, primary_key = True)
name = alchemyDB.Column(alchemyDB.String(64), unique = True)
default = alchemyDB.Column(alchemyDB.Boolean, default = False, index = True)
permissions = alchemyDB.Column(alchemyDB.Integer)
users = alchemyDB.relationship('User', backref='role', lazy='dynamic')
def __repr__(self):
return '<Role $r>'%self.name
@staticmethod
def setRolesInDB(app):
'''
sets the basic roles in the database
'''
roles = {
'User' : (Permission.WRITE_ARTICLES, True),
'Moderator' : (Permission.WRITE_ARTICLES | Permission.MODERATE_COMMENTS, False),
'Administrator' : (0xff, False)
}
with app.app_context():
with alchemyDB.session.no_autoflush:
for r in roles :
role = Roles.query.filter_by(name = r).first()
if role == None :
role = Roles(name = r)
role.permissions = roles[r][0]
role.default = roles[r][1]
alchemyDB.session.add(role)
alchemyDB.session.commit()
class User(UserMixin, alchemyDB.Model):
__tablename__ = 'users'
id = alchemyDB.Column(alchemyDB.Integer, primary_key = True)
user_email = alchemyDB.Column(alchemyDB.String(64), unique = True, index = True)
user_name = alchemyDB.Column(alchemyDB.String(64), unique = True, index = True)
user_pass = alchemyDB.Column(alchemyDB.String(128))
role_id = alchemyDB.Column(alchemyDB.Integer, alchemyDB.ForeignKey('roles.id'))
communities = alchemyDB.Column(alchemyDB.String(64))
articles_compared = alchemyDB.Column(alchemyDB.String(64))
date_joined = alchemyDB.Column(alchemyDB.DateTime)
user_tags = alchemyDB.relationship('UsersAppliedTags',
foreign_keys = [UsersAppliedTags.user_id],
backref = alchemyDB.backref('users_who_have_used_this_tag_for_this_article', lazy ='joined'),
lazy = 'dynamic',
cascade = 'all, delete-orphan')
以下是我如何调用该函数:
alchemyDB.init_app(app)
with app.app_context():
# Extensions like Flask-SQLAlchemy now know what the "current" app
# is while within this block. Therefore, you can now run........
alchemyDB.create_all()
Roles.setRolesInDB(app)
我收到以下错误:
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError:(IntegrityError)roles.id可能不是 NULL u'INSER T INTO角色(名称,“默认”,权限)VALUES(?,?, ?)'('主持人',0,1 2)
此表与其他表一样,我从未遇到主键突然未自动增加的问题。这可能会出现什么问题?
根据请求,这是表格在数据库中的样子:
sqlite> pragma table_info(Roles);
0|id|VARCHAR(64)|1||1
1|name|VARCHAR(64)|0||0
2|default|BOOLEAN|0||0
3|permissions|INTEGER|0||0
答案 0 :(得分:2)
将id
列的类型更改为INTEGER
并将其设为autoincrement
。