When I create a user with User class, for example
User(username='xxx',password='xxxx', role =[Role(name='Admin'),])
Database will also add to Role table a row with name Admin.
The issue is when I create another user with role Admin and it will cast error UNIQUE constraint failed: roles.name. How can I prevent this ?
Here is my code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///user.db'
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer(),primary_key = True)
username = db.Column(db.String(20),unique = True, nullable = False)
password = db.Column(db.String(50),unique = False, nullable = False)
role = db.relationship('Role',secondary = 'userroles', backref = db.backref('user',lazy = 'dynamic'))
class Role(db.Model):
__tablename__ = 'roles'
role_id = db.Column(db.Integer(),primary_key = True)
name = db.Column(db.String(20), unique = True)
class UserRole(db.Model):
__tablename__ = 'userroles'
id = db.Column(db.Integer(), primary_key = True)
user_id = db.Column(db.Integer(),db.ForeignKey('users.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(),db.ForeignKey('roles.role_id', ondelete='CASCADE'))