In my web application users and workers can login and I have 2 different models for them. However, when I try to create a user_loader method for the worker model I receive and error
Here is my code
@login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) @login_manager.worker_loader def load_worker(worker_id): return Worker.query.get(int(user_id)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) fname = db.Column(db.String(30), nullable=False) lname = db.Column(db.String(30), nullable=False) phone = db.Column(db.String(11), unique=True, nullable=False) email = db.Column(db.String(25), unique=True, nullable=False) location = db.Column(db.String(15), nullable=False) password = db.Column(db.String(60), nullable=False) mode = db.Column(db.String(10), nullable=False, default='User') address = db.relationship('Address', backref='user_address', lazy=True) workorder = db.relationship('JobLog', backref='order', lazy=True) class Worker(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) fname = db.Column(db.String(30), nullable=False) lname = db.Column(db.String(30), nullable=False) phone = db.Column(db.String(11), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) location = db.Column(db.String(15), nullable=False) job = db.Column(db.String(20), nullable=False) description = db.Column(db.Text, nullable=False, default='Insert your personal description here') image = db.Column(db.String(20), nullable=False, default='default.jpg') password = db.Column(db.String(60), nullable=False) mode = db.Column(db.String(10), nullable=False, default='Worker') active = db.Column(db.Boolean, nullable=False, default=False) workrequest = db.relationship('JobLog', backref='request', lazy=True)
Advertisement
Answer
@login_manager.user_loader
is a decorator present in the login_manager
class – it does not represent different types of users (i.e. user
and worker
) – so you’d have to refer to it as the user_loader
in both cases.
But here’s the issue – you can’t know if you’re supposed to retrieve a worker or a user from the user id alone. Since workers effectively are users, don’t have two models – merge the common properties into a single model, and keep the worker related data in a separate model with a relationship between them (or make them nullable on the user model to keep it simpler).
You already have a field telling you if the user is a regular user or a worker, so I’d go with merging it into a single model. You can keep the reference between worker and job through the same mechanism you have today (set workorder if they’re a user, set workrequest if they’re a worker) or you can create a many-to-many-relationship between the JobLog and the User table instead – and use the User type to determine if they’re a supervisor or a worker.