models.py 2.79 KB


from sqlalchemy import Table, Column, ForeignKey, Integer, Float, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship


# ===========================================================================
#   Declare ORM
Base = declarative_base()

# ---------------------------------------------------------------------------
class StudentTopic(Base):
    __tablename__ = 'studenttopic'
    student_id = Column(String, ForeignKey('students.id'), primary_key=True)
    topic_id = Column(String, ForeignKey('topics.id'), primary_key=True)
    level = Column(Float)
    date  = Column(String)

    # ---
    student = relationship('Student', back_populates='topics')
    topic = relationship('Topic', back_populates='students')

# ---------------------------------------------------------------------------
# Registered students
# ---------------------------------------------------------------------------
class Student(Base):
    __tablename__ = 'students'
    id = Column(String, primary_key=True)
    name = Column(String)
    password = Column(String)

    # ---
    answers = relationship('Answer', back_populates='student')
    topics = relationship('StudentTopic', back_populates='student')

    def __repr__(self):
        return f'''Student:
            id:         "{self.id}"
            name:       "{self.name}"
            password:   "{self.password}"'''

# ---------------------------------------------------------------------------
# Table with every answer given
# ---------------------------------------------------------------------------
class Answer(Base):
    __tablename__ = 'answers'
    id = Column(Integer, primary_key=True) # auto_increment
    ref = Column(String)
    grade = Column(Float)
    starttime = Column(String)
    finishtime = Column(String)
    student_id = Column(String, ForeignKey('students.id'))
    topic_id = Column(String, ForeignKey('topics.id'))

    # ---
    student = relationship('Student', back_populates='answers')
    topic = relationship('Topic', back_populates='answers')

    def __repr__(self):
        return '''Question:
            id:         "{self.id}"
            ref:        "{self.ref}"
            grade:      "{self.grade}"
            starttime:  "{self.starttime}"
            finishtime: "{self.finishtime}"
            student_id: "{self.student_id}"'''

# ---------------------------------------------------------------------------
# Table with student state
# ---------------------------------------------------------------------------
class Topic(Base):
    __tablename__ = 'topics'
    id = Column(String, primary_key=True)

    # ---
    students = relationship('StudentTopic', back_populates='topic')
    answers = relationship('Answer', back_populates='topic')

    # def __init__(self, id):
    #     self.id = id