Python 主键列为';sqlalchemy中的t自动插入(IntegrityError)
我有一个sqlalchemy模型和一个向表中添加一些元素的方法。以下是模型和功能:Python 主键列为';sqlalchemy中的t自动插入(IntegrityError),python,sqlalchemy,Python,Sqlalchemy,我有一个sqlalchemy模型和一个向表中添加一些元素的方法。以下是模型和功能: class Roles(alchemyDB.Model): __tablename__ = 'roles' id = alchemyDB.Column(alchemyDB.Integer, primary_key = True) name = alchemyDB.Column(alchemyDB.String(64), unique = True) default = alchem
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')
我得到以下错误:
sqlalchemy.exc.IntegrityError:(IntegrityError)roles.id不能为空
在角色(名称,“默认”,权限)值(?,,,中插入空u'insert T?,
(“主持人”,0,12)
这个表和其他表一样,我从来没有遇到过主键突然不自动递增的问题。这里可能出了什么问题
根据请求,以下是该表在数据库中的外观:
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
将
id
列的类型更改为INTEGER
,并使其autoincrement
显示直接表结构(在数据库中)Tomasz,您的意思是在我的帖子中显示我的所有表吗?不,只有角色表我为角色表添加了表信息。我想我把模型从一个字符串主键(这是一个错误)改成了一个整数。如果你发现这是一个错误,请张贴,我会标记为答案。托马斯兹,我发现了问题,你的要求直接指导我,谢谢。
cursor.execute(statement, parameters)
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