0

I have three user types which I intend to store in three different database tables. The structure is as follows:

  • A master table that contains columns id, teacher_userid, student_userid, parent_userid, role and a few other columns.
  • A teacher table containing details about a teacher user (including login credentials)
  • A student table containing details about a student user (including login credentials)
  • A parent table containing details about a parent user (including login credentials)

The reason for having three separate tables is that the data stored for each will be quite different and it seems cleaner to do it this way.

I want users of any type to be able to sign in through the same form in my Flask app. flask-login should look up the master table, which should then pull data from the relevant teacher, student or parent table to populate the User model.

However, I'm stumped as to how to populate the User model conditionally with data from the other tables.

The ideal scenario is to be able to add something like this to the User(db.model):

if 'Teacher' in role:
  name = teacher.name
  email = teacher.email

elif 'Student in role:
  name = student.name
  email = student.email

And so on. However, it does not appear to be possible to use conditional statements like that within the definition of the User class. Are getters and setters the solution? It all feels quite messy.

Rob
  • 78
  • 1
  • 2
  • 23
  • 1
    I think what you may be looking for is: [Mapping Class Inheritance Hierarchies](https://docs.sqlalchemy.org/en/13/orm/inheritance.html). – v25 Jan 25 '20 at 17:42
  • Additionally [this SO thread](https://stackoverflow.com/questions/15871391/implementing-flask-login-with-multiple-user-classes) has some relevant info. – v25 Jan 25 '20 at 17:54

1 Answers1

0

I would suggest you store the common data fields - such as credentials - in the 'master' user table, and only role specific fields in the teacher, parent, student tables.

The teacher, parent, student tables should have a reference back to the user table.

You can add properties to your flask-sqlalchemy User class called teacher, student, and parent that return the related Teacher, Student, Parent objects (a Teacher may also be a Parent perhaps).

This model allows your User related code (such as login) to run against User objects, and your role specific code to run against role specific objects.

DaveH
  • 1
  • 1