我看不懂这个报错,貌似是外键问题不知道哪里写错了
来源:5-1 .前台布局搭建
拓跋宇
2017-09-28
# Author: wengwenyu from flask import Flask from flask_sqlalchemy import SQLAlchemy from datetime import datetime import pymysql app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql+pymysql://root:rootwwy@127.0.0.1:3306/movie' app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True db = SQLAlchemy(app) #会员 class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer,primary_key=True)#编号 name = db.Column(db.String(100),unique=True)#昵称 pwd = db.Column(db.String(100))#密码 email = db.Column(db.String(100),unique=True)#邮箱 phone = db.Column(db.String(11),unique=True)#手机号 info = db.Column(db.Text)#个性简介 face = db.Column(db.String(255),unique=True)#头像 addtime = db.Column(db.DateTime,index=True,default=datetime.now) uuid = db.Column(db.String(255),unique=True)#唯一标识符 userlogs = db.relationship('Userlog',backref='user')#会员日志外键关系的关联 comments = db.relationship('Comment',backref='user')#评论外键关联 moviecols = db.relationship("Moviecol",backref='user')#收藏外键关联 def __repr__(self): return "<User %r>" % self.name #会员登录日志 class Userlog(db.Model): __tablename___ = 'userlog' id = db.Column(db.Integer,primary_key=True)#编号 user_id = db.Column(db.Integer,db.ForeignKey('user.id'))#所属会员 ip = db.Column(db.String(100))#登录ip addtime = db.Column(db.DateTime,index=True,default=datetime.now)#登录时间 def __repr__(self): return '<Userlog %r>'%self.id #标签 class Tag(db.Model): __tablename__ = 'tag' id = db.Column(db.Integer,primary_key=True)#编号 name =db.Column(db.String(100),unique=True)#标题 addtime = db.Column(db.DateTime,index=True,default=datetime.now)#添加时间 movies = db.relationship("Movie",backref="tag")#电影外键关系的关联 def __repr__(self): return '<Tag %r>'% self.name #电影 class Movie(db.Model): __tablename__ = "movie" id = db.Column(db.Integer,primary_key=True)#编号 title = db.Column(db.String(255),unique=True)#标题 url = db.Column(db.String(255), unique=True)#地址 info = db.Column(db.Text)#简介 logo = db.Column(db.String(255), unique=True)#封面 star = db.Column(db.SmallInteger)#星级 playnum = db.Column(db.BigInteger)#播放量 commentnum = db.Column(db.BigInteger)#评论量 tag_id = db.Column(db.Integer,db.ForeignKey('tag.id'))#所属标签 area = db.Column(db.String(255))#上映地区 release_time = db.Column(db.Date)#上映时间 length = db.Column(db.String(100))#播放时长 addtime = db.Column(db.DateTime,index=True,default=datetime.now)#添加时间 comments = db.relationship("Comment",backref='movie')#电影外键关系关联 moviecols = db.relationship("Moviecol", backref='movie') # 收藏外键关系关联 def __repr__(self): return "<Movie %r>" % self.title #上映预告 class Preview(db.Model): __tablename__ = 'preview' id = db.Column(db.Integer,primary_key=True) title = db.Column(db.String(255), unique=True) # 标题 logo = db.Column(db.String(255), unique=True) # 封面 addtime = db.Column(db.DateTime, index=True, default=datetime.now) # 添加时间 def __repr__(self): return "<Preview %r>" % self.title #评论 class Comment(db.Model): __tablename__ = 'comment' id = db.Column(db.Integer,primary_key=True)#编号 content = db.Column(db.Text)#评论的内容 movie_id = db.Column(db.Integer,db.ForeignKey('movie.id'))#所属电影 user_id = db.Column(db.Integer,db.ForeignKey('user.id'))#所属用户 addtime = db.Column(db.DateTime, index=True, default=datetime.now) # 添加时间 def __repr__(self): return "<Comment %r>" % self.title #电影收藏 class Moviecol(db.Model): __tablename__ = "moviecol" id = db.Column(db.Integer, primary_key=True) # 编号 movie_id = db.Column(db.Integer, db.ForeignKey('movie.id')) # 所属电影 user_id = db.Column(db.Integer, db.ForeignKey('user.id')) # 所属用户 def __repr__(self): return "<Moviecol %r>" % self.id #权限 class Auth(db.Model): __tablename__ = "auth" id = db.Column(db.Integer, primary_key=True) # 编号 name = db.Column(db.String(100),unique=True)#名称 url =db.Column(db.String(255),unique=True)#地址 addtime = db.Column(db.DateTime, index=True, default=datetime.now) # 添加时间 def __repr__(self): return "<Auth %r>" % self.id #角色 class Role(db.Model): __tablename__ = 'role' id = db.Column(db.Integer, primary_key=True) # 编号 name = db.Column(db.String(100), unique=True) # 名称 auths = db.Column(db.String(600)) addtime = db.Column(db.DateTime, index=True, default=datetime.now) # 添加时间 admins = db.relationship("Admin", backref='role') # def __repr__(self): return "<Role %r>" % self.name # 管理员 class Admin(db.Model): __tablename__ = 'admin' id = db.Column(db.Integer, primary_key=True) # 编号 name = db.Column(db.String(100), unique=True) # 管理员账号 pwd = db.Column(db.String(100)) # 管理员密码 is_super = db.Column(db.SmallInteger)#是否为超级管理员,0超级管理员 role_id = db.Column(db.Integer,db.ForeignKey('role.id'))#所属角色 addtime = db.Column(db.DateTime, index=True, default=datetime.now) # 添加时间 adminlogs = db.relationship("Adminlog",backref='admin')#管理员登入日志外键关系关联 oplogs = db.relationship("Oplog", backref='admin') #操作日志外键关系关联 def __repr__(self): return "<Admin %r>" % self.name #登入日志 class Adminlog(db.Model): __tablename__ = 'adminlog' id = db.Column(db.Integer, primary_key=True) # 编号 admin_id = db.Column(db.Integer, db.ForeignKey('admin.id')) # 所属管理员 ip = db.Column(db.String(100)) # 登录ip addtime = db.Column(db.DateTime, index=True, default=datetime.now) # 登录时间 def __repr__(self): return "<Adminlog %r>" % self.id #操作日志 class Oplog(db.Model): __tablename__ = 'oplog' id = db.Column(db.Integer, primary_key=True) # 编号 admin_id = db.Column(db.Integer, db.ForeignKey('admin.id')) # 所属管理员 ip = db.Column(db.String(100)) # 登录ip reason = db.Column(db.String(600))#操作原因 addtime = db.Column(db.DateTime, index=True, default=datetime.now) # 登录时间 def __repr__(self): return "<Oplog %r>" % self.id if __name__ == '__main__': db.create_all() # role = Role( # name='超级管理员', # auths='' # ) # db.session.add(role) # db.session.commit() from werkzeug.security import generate_password_hash # admin = Admin( # name='imooc', # pwd=generate_password_hash('imooc'), # is_super=0, # role_id=1 # ) # db.session.add(admin) # db.session.commit()
sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`movie`.`admin`, CONSTRAINT `admin_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`))') [SQL: 'INSERT INTO `admin` (name, pwd, is_super, role_id, addtime) VALUES (%(name)s, %(pwd)s, %(is_super)s, %(role_id)s, %(addtime)s)'] [parameters: {'pwd': 'pbkdf2:sha256:50000$7mfY9hcG$dfaf38ef2850d23557fed50bbc3408911e3074ce9ef7e5030e8a38e9c17b41dd', 'role_id': 1, 'addtime': datetime.datetime(2017, 9, 28, 15, 7, 40, 421093), 'is_super': 0, 'name': 'imooc'}]
Process finished with exit code 1
写回答
1回答
-
拓跋宇
提问者
2017-09-28
C:\ProgramData\Anaconda3\envs\flask_env\python.exe C:/Users/wengw/PycharmProjects/movie_project/app/models.py C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\cursors.py:166: Warning: (1366, "Incorrect string value: '\\xD6\\xD0\\xB9\\xFA\\xB1\\xEA...' for column 'VARIABLE_VALUE' at row 480") result = self._query(query) Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\engine\base.py", line 1182, in _execute_context context) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\engine\default.py", line 470, in do_execute cursor.execute(statement, parameters) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\cursors.py", line 166, in execute result = self._query(query) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\cursors.py", line 322, in _query conn.query(q) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\connections.py", line 856, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\connections.py", line 1057, in _read_query_result result.read() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\connections.py", line 1340, in read first_packet = self.connection._read_packet() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\connections.py", line 1014, in _read_packet packet.check_error() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\connections.py", line 393, in check_error err.raise_mysql_exception(self._data) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`movie`.`admin`, CONSTRAINT `admin_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`))') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:/Users/wengw/PycharmProjects/movie_project/app/models.py", line 193, in <module> db.session.commit() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\scoping.py", line 157, in do return getattr(self.registry(), name)(*args, **kwargs) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\session.py", line 906, in commit self.transaction.commit() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\session.py", line 461, in commit self._prepare_impl() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\session.py", line 441, in _prepare_impl self.session.flush() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\session.py", line 2177, in flush self._flush(objects) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\session.py", line 2297, in _flush transaction.rollback(_capture_exception=True) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\util\langhelpers.py", line 66, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\util\compat.py", line 187, in reraise raise value File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\session.py", line 2261, in _flush flush_context.execute() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 389, in execute rec.execute(self) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 548, in execute uow File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\persistence.py", line 181, in save_obj mapper, table, insert) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\orm\persistence.py", line 835, in _emit_insert_statements execute(statement, params) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\engine\base.py", line 945, in execute return meth(self, multiparams, params) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\sql\elements.py", line 263, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\engine\base.py", line 1053, in _execute_clauseelement compiled_sql, distilled_params File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\engine\base.py", line 1189, in _execute_context context) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\engine\base.py", line 1402, in _handle_dbapi_exception exc_info File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\util\compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\util\compat.py", line 186, in reraise raise value.with_traceback(tb) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\engine\base.py", line 1182, in _execute_context context) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\sqlalchemy\engine\default.py", line 470, in do_execute cursor.execute(statement, parameters) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\cursors.py", line 166, in execute result = self._query(query) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\cursors.py", line 322, in _query conn.query(q) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\connections.py", line 856, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\connections.py", line 1057, in _read_query_result result.read() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\connections.py", line 1340, in read first_packet = self.connection._read_packet() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\connections.py", line 1014, in _read_packet packet.check_error() File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\connections.py", line 393, in check_error err.raise_mysql_exception(self._data) File "C:\ProgramData\Anaconda3\envs\flask_env\lib\site-packages\pymysql\err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`movie`.`admin`, CONSTRAINT `admin_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`))') [SQL: 'INSERT INTO `admin` (name, pwd, is_super, role_id, addtime) VALUES (%(name)s, %(pwd)s, %(is_super)s, %(role_id)s, %(addtime)s)'] [parameters: {'pwd': 'pbkdf2:sha256:50000$7mfY9hcG$dfaf38ef2850d23557fed50bbc3408911e3074ce9ef7e5030e8a38e9c17b41dd', 'role_id': 1, 'addtime': datetime.datetime(2017, 9, 28, 15, 7, 40, 421093), 'is_super': 0, 'name': 'imooc'}] Process finished with exit code 1
022018-03-13
相似问题