Tri
Tri

Reputation: 3039

Can I have array enum column with Flask-SQLAlchemy..?

I have a case to make a student course, which also contains schedules for students. And I making a schedule model with Flask-SQLAlchemy and use PostgreSQL as its database.

here is the snippet of my current code:

class DayNameList(enum.Enum):
    Sunday = 'Sunday'
    Monday = 'Monday'
    Tuesday = 'Tuesday'
    Wednesday = 'Wednesday'
    Thursday = 'Thursday'
    Friday = 'Friday'
    Saturday = 'Saturday'

    def __str__(self):
        return self.value

class Schedule(db.Model):
    __tablename__ = 'schedule'
    id = db.Column(db.Integer, primary_key=True)
    schedule_day = db.Column(db.Enum(DayNameList, name='schedule_day'))
    start_at = db.Column(db.Time())
    end_at = db.Column(db.Time())
    # ...
    # ...

In my case there is two schedule day for each week for students.

In my current code, the schedule_day column is an Enum type.

So, my questions are, should I making the schedule_day to be an ARRAY Enum ..?, if so how about the start_at and end_at column..?, should I also convert its to ARRAY..? and any example how to do that..?

Or should I add a new column, i.e schedule_day_2 or what..?

What is the best practice..? Any help would be appreciate, Thanks :)

Upvotes: 3

Views: 762

Answers (1)

stasiekz
stasiekz

Reputation: 1863

Consider creating separate model for ScheduleDay which could be related with your Schedule with One-to-Many relationship.

class Schedule(db.Model):
    __tablename__ = 'schedule'
    id = db.Column(db.Integer, primary_key=True)
    days = db.relationship('ScheduleDay', backref='schedule', lazy=True)
    # ...
    # ...

class ScheduleDay(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    day = db.Column(db.Enum(DayNameList, name='schedule_day'))
    start_at = db.Column(db.Time())
    end_at = db.Column(db.Time())
    schedule_id = db.Column(db.Integer, db.ForeignKey('schedule.id'),
        nullable=False)

In case some week will have more than 2 days then you can easily add more of them.

Example:

>>> schedule = Schedule()
>>> db.session.add(schedule)
>>> db.session.commit()
>>> from datetime import time
>>> monday_schedule = ScheduleDay(day=DayNameList.Monday, start_at=time(10, 15), end_at=time(12, 15), schedule_id=schedule.id)
>>> db.session.add(monday_schedule)
>>> tuesday_schedule = ScheduleDay(day=DayNameList.Tuesday, start_at=time(15, 15), end_at=time(17, 15), schedule_id=schedule.id)
>>> db.session.add(tuesday_schedule)
>>> db.session.commit()
>>> schedule.days
[<ScheduleDay 1>, <ScheduleDay 2>]
>>> schedule.days[0].day
<DayNameList.Monday: 'Monday'>
>>> schedule.days[1].day
<DayNameList.Tuesday: 'Tuesday'>

Upvotes: 2

Related Questions