class CourseSections(db.Model): __tablename__ = 'course_sections' id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(20)) name = db.Column(db.String(50)) course_id = db.Column(db.Integer, db.ForeignKey('courses.id')) teacher_id = db.Column(db.Integer, db.ForeignKey('users.id')) course_section_period = db.Column(db.String(6)) section_times = db.relationship("SectionTimes", backref='course_section', lazy='dynamic') __table_args__ = (db.UniqueConstraint('course_id', 'teacher_id', 'course_section_period', 'code', name='course_section_period_uc'), ) def __str__(self): return str('{0} - {1}').format( str(Courses.query.get(self.course_id).code), str(self.course_section_period)) def set_fields(self, fields): self.code = fields['code'] self.name = fields['name'] self.course_id = fields['course_id'] self.teacher_id = fields['teacher_id'] self.course_section_period = fields['course_section_period']
class WallMessages(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) date = db.Column(db.Integer) sender = db.Column(db.Integer, db.ForeignKey("users.id")) destination = db.Column(db.Integer, db.ForeignKey("user_type_destinations.id")) param_value = db.Column(db.Integer()) message = db.Column(db.Text()) def set_fields(self, fields): self.date = fields['date'] self.sender = fields['sender'] self.destination = fields['user_type_destination_id'] self.param_value = fields['parameter'] self.message = format_urls_in_text(fields['message']) def get_sender(self): return Users.query.filter_by(id=self.sender).all() def get_destinations(self): _dict = {} query = UserTypeDestinations.query.filter_by( id=self.destination).first().users_query query = str(query).replace('$', str(self.param_value)) exec(query, _dict) return _dict['users']
class UserSong(db.Model): __tablename__ = 'user_song' user_id = db.Column('user_id', db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE'), primary_key=True) song_id = db.Column('song_id', db.Integer(), db.ForeignKey('song.id', ondelete='RESTRICT'), primary_key=True) time_played = db.Column('time_played', db.DateTime(), primary_key=True) user = db.relationship("User", backref=db.backref('user_song', lazy='dynamic')) song = db.relationship("Song") def __init__(self, user, song, time_played): self.user = user self.song = song self.time_played = time_played def __repr__(self): return '<User %s Song %s>' % (self.user.username, self.song.spot_id)
class Subscribe(db.Model): id = db.Column(db.Integer, unique=True, primary_key=True) post_id = db.Column(db.Integer, db.ForeignKey('travel.id', ondelete='CASCADE')) subscriber_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE')) notifications = db.relationship('Notification', backref='subscribe', cascade='all, delete-orphan', passive_deletes=True) follow_id = db.Column(db.Integer, db.ForeignKey('follow.id', ondelete='CASCADE'), nullable=False) def to_json(self): json_sub = { 'post_id': self.post_id, 'subscriber_id': self.subscriber_id, 'notifications': [{ 'date': i.date_posted, 'id': i.id } for i in self.notifications] } return json_sub
class Match(db.Model): __tablename__ = 'match' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) description = db.Column(db.String(200)) userId = db.Column(db.Integer, db.ForeignKey('user.id')) opponentId = db.Column(db.Integer, db.ForeignKey('user.id')) userTime = db.Column(db.Float) userDistance = db.Column(db.Float) opponentTime = db.Column(db.Float) opponentDistance = db.Column(db.Float) locationName = db.Column(db.String(50)) locationLatitude = db.Column(db.Float) locationLongitude = db.Column(db.Float) state = db.Column(db.Integer) def __init__( self, name, description, userId, opponentId, userTime, userDistance, opponentTime, opponentDistance, locationName, locationLatitude, locationLongitude, state ): self.name = name self.description = description self.userId = userId self.opponentId = opponentId self.userTime = userTime self.userDistance = userDistance self.opponentTime = opponentTime self.opponentDistance = opponentDistance self.locationName = locationName self.locationLatitude = locationLatitude self.locationLongitude = locationLongitude self.state = state
class Tag(db.Model): """ A database model class to store information about tags. ... Attributes ---------- id : int ID of the class keyword : str Keyword indicating user preference user_id : int User ID of the query creator, as stored in User table """ id = db.Column(db.Integer, primary_key=True) keyword = db.Column(db.String(127), nullable=False) query_id = db.Column(db.Integer, db.ForeignKey('query.id'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) def __init__(self, keyword: str, query_id: int, user_id: int): """ Parameters ---------- keyword : str Keyword indicating user preference query_id : int Query ID of the query creator, as stored in User table user_id : int User ID of the query creator, as stored in User table """ self.keyword = keyword self.query_id = query_id self.user_id = user_id
class Follow(db.Model): id = db.Column(db.Integer, primary_key=True, unique=True) follower_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False) followed_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False) subscribes = db.relationship('Subscribe', backref='follow', lazy='dynamic', cascade='all, delete-orphan', passive_deletes=True) def to_json(self): json_user = { 'follower_id': self.follower_id, 'followed_id': self.followed_id, 'follower_username': self.follower.username, 'followed_username': self.followed.username, 'follower_image': self.follower.image_file, 'followed_image': self.followed.image_file, 'subscribed_travels': len(self.subscribes.all()) } return json_user
class ProjectTeams(db.Model): __tablename__ = "project_teams" team_id = db.Column(db.Integer, db.ForeignKey("teams.id"), primary_key=True) project_id = db.Column(db.Integer, db.ForeignKey("projects.id"), primary_key=True) role = db.Column(db.Integer, nullable=False) project = db.relationship("Project", backref=db.backref("teams", cascade="all, delete-orphan")) team = db.relationship(Team, backref=db.backref("projects", cascade="all, delete-orphan")) def create(self): """ Creates and saves the current model to the DB """ db.session.add(self) db.session.commit() def save(self): """ Save changes to db""" db.session.commit() def delete(self): """ Deletes the current model from the DB """ db.session.delete(self) db.session.commit()
class CoursePrerequisites(db.Model): id = db.Column(db.Integer, primary_key=True, nullable=False, autoincrement=True) program_id = db.Column(db.Integer, db.ForeignKey('program.id'), nullable=False) course_id_from = db.Column(db.Integer, db.ForeignKey('courses.id'), nullable=False) course_id_to = db.Column(db.Integer, db.ForeignKey('courses.id'), nullable=False) def serialize(self): return { 'id': self.id, 'program_id': self.program_id, 'course_id_from': self.course_id_from, 'course_id_to': self.course_id_to } def set_fields(self, fields): self.program_id = fields['program_id'] self.course_id_from = fields['course_id_from'] self.course_id_to = fields['course_id_to']
class Invoice_product(db.Model): __tablename__ = 'invoices_products' id = db.Column(db.Integer, primary_key=True) invoice_id = db.Column(db.Integer, db.ForeignKey('invoices.id')) product_id = db.Column(db.Integer, db.ForeignKey('products.id')) qty = db.Column(db.Integer) def __init__(self, invoice_id, product_id, qty): self.invoice_id = invoice_id self.product_id = product_id self.qty = qty #one list id has many invoices, this refers to the invoices table # invoices = db.relationship('Invoice',backref='inoices') # #one invoice has many products, this refers to the products table # # Error: On relationship Invoice_product.invoices, 'dynamic' loaders cannot be used with many-to-one/one-to-one relationships and/or uselist=False. # products = db.relationship('Product', backref='products') def serialize(self): return { 'id': self.id, 'invoice_id': self.invoice_id, 'item_id': self.product_id, 'qty': self.qty }
class BlogComment(db.Model): id = db.Column(db.Integer, primary_key=True) created = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now()) modified = db.Column(db.DateTime, server_default=db.func.now()) # title = db.Column(db.String(128)) author = db.Column(db.String(128)) author_email = db.Column(db.String(128)) author_website = db.Column(db.String(128), nullable=True) content = db.Column(db.Text) by_author = db.Column(db.Boolean, default=False) replied_to_id = db.Column(db.Integer, db.ForeignKey('blog_comment.id'), index=True) replied_to = db.relationship(lambda: BlogComment, remote_side=id, backref=db.backref('sub_comments', lazy='dynamic')) post_id = db.Column(db.Integer, db.ForeignKey(BlogPost.id), index=True) post = db.relationship(BlogPost, backref=db.backref('comments', lazy='dynamic'))
class TeamMembers(db.Model): __tablename__ = "team_members" team_id = db.Column(db.Integer, db.ForeignKey("teams.id", name="fk_teams"), primary_key=True) user_id = db.Column(db.BigInteger, db.ForeignKey("users.id", name="fk_users"), primary_key=True) function = db.Column(db.Integer, nullable=False) # either 'editor' or 'manager' active = db.Column(db.Boolean, default=False) member = db.relationship(User, backref=db.backref("teams", cascade="all, delete-orphan")) team = db.relationship("Team", backref=db.backref("members", cascade="all, delete-orphan")) def create(self): """ Creates and saves the current model to the DB """ db.session.add(self) db.session.commit() def delete(self): """ Deletes the current model from the DB """ db.session.delete(self) db.session.commit()
class PrivilegesRolesModel(db.Model): __tablename__ = 'tbl_privileges_x_roles' id_role = db.Column(db.Integer, db.ForeignKey('tbl_roles.id_role'), primary_key=True) id_privilege = db.Column(db.Integer, db.ForeignKey('tbl_privileges.id'), primary_key=True) def __init__(self, id_rol, id): self.id_role = id_rol self.id_privilege = id def json(self): return {'id_rol': self.id_role, 'id_privilege': self.id_privilege} def insert(self): db.session.add(self) db.session.commit() @classmethod def bring_all(cls): return cls.query.all() def delete_item(self): db.session.delete(self) db.session.commit()
class Follow(db.Model): follower_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) followed_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) timestamp = db.Column(db.DateTime, default=datetime.utcnow) def __repr__(self): return f"Follow('{self.timestamp}')"
class Users(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20)) email = db.Column(db.String(50), unique=True) password = db.Column(db.String(50)) name = db.Column(db.String(250)) birth_date = db.Column(db.Date()) gender = db.Column(db.String(1)) address = db.Column(db.String(250)) push_notification_token = db.Column(db.Text(), nullable=True) type = db.Column(db.Integer, db.ForeignKey('user_type.id')) program_id = db.Column(db.Integer, db.ForeignKey('program.id'), nullable=True) image_path = db.Column(db.Text(), nullable=True) course_sections = db.relationship('CourseSectionStudents', cascade="save-update, merge, delete") def set_fields(self, fields): self.username = fields.get('username') self.email = fields.get('email') self.password = self.password if self.password else fields.get( 'password') self.name = fields.get('name') self.gender = fields.get('gender') self.address = fields.get('address') self.birth_date = datetime.datetime.strptime( fields.get('birth_date'), "%m-%d-%Y").date() if fields.get('birth_date') else None self.program_id = fields.get('program_id') self.type = self.type if self.type else fields.get('type') def save_image(self, file): file_name, _format = str(file.filename).rsplit('.', 1) user_name, domain = str(self.email).split('@', maxsplit=1) if not _format in settings.ALLOWED_EXTENSIONS: _format = 'jpg' files = {'image_file': file} headers = {"enctype": "multipart/form-data"} r = requests.post( 'http://eliakimdjango.pythonanywhere.com/save_profile_image', files={ 'file': (user_name + str(random.randint(1000, 10000)) + '.' + _format, file, headers, { 'Expires': '0' }) }, data={'old_file_path': self.image_path}) # r = requests.post('http://127.0.0.1:2000/save_profile_image', # files={'file': (self.username + str(random.randint(1000, 10000)) + '.' + _format, file, # headers, {'Expires': '0'})}, # data={'old_file_path': self.image_path}) if r.status_code == 200: self.image_path = r.json()['result'] return True
class StudentAttendance(db.Model): id = db.Column(db.Integer, primary_key=True) section_time_id = db.Column(db.Integer, db.ForeignKey('section_times.id')) course_section_student_id = db.Column( db.Integer, db.ForeignKey('course_section_students.id')) status = db.Column(db.String(1)) section_time_date = db.Column(db.Date()) course_section_student = db.relationship("CourseSectionStudents")
class Notification(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) post_id = db.Column(db.Integer, db.ForeignKey('posts.id')) timestamp = db.Column(db.DateTime, default=datetime.utcnow) kind = db.Column(db.String(10), nullable=False) def __repr__(self): return f"Notification('{self.user_id}', '{self.post_id}')"
class Notification(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), nullable=False) viewed = db.Column(db.Boolean, nullable=False) def __repr__(self): return f"Notification('{self.user_id}','{self.post_id}')"
class Like(db.Model): id = db.Column(db.Integer, primary_key=True) post_id = db.Column(db.Integer, db.ForeignKey('post.id')) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) comment_id = db.Column(db.Integer, db.ForeignKey('comment.id')) def __repr__(self): return f'{self.user_id}'
class Fav(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) res_id = db.Column(db.Integer, db.ForeignKey('result.id'), nullable=False) status = db.Column(db.Boolean, nullable=False, default=True) def __repr__(self): return f"Favorite Relationship ID {self.id}"
class Paring(db.Model): '''Represents tournament parring.''' __tablename__ = 'paring' id = db.Column(db.Integer, primary_key=True, autoincrement=True) participant_id = db.Column(db.ForeignKey(Participant.id), nullable=False) participant2_id = db.Column(db.ForeignKey(Participant.id), nullable=False) tournament_id = db.Column(db.ForeignKey(Tournament.id), nullable=False)
class ProjectChat(db.Model): """ Contains all project info localized into supported languages """ __tablename__ = "project_chat" id = db.Column(db.BigInteger, primary_key=True) project_id = db.Column( db.Integer, db.ForeignKey("projects.id"), index=True, nullable=False ) user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) time_stamp = db.Column(db.DateTime, nullable=False, default=timestamp) message = db.Column(db.String, nullable=False) # Relationships posted_by = db.relationship(User, foreign_keys=[user_id]) @classmethod def create_from_dto(cls, dto: ChatMessageDTO): """ Creates a new ProjectInfo class from dto, used from project edit """ current_app.logger.debug("Create chat message from DTO") new_message = cls() new_message.project_id = dto.project_id new_message.user_id = dto.user_id # Use bleach to remove any potential mischief clean_message = bleach.clean(dto.message) clean_message = bleach.linkify(clean_message) new_message.message = clean_message db.session.add(new_message) return new_message @staticmethod def get_messages(project_id: int, page: int, per_page: int = 20) -> ProjectChatDTO: """ Get all messages on the project """ project_messages = ( ProjectChat.query.filter_by(project_id=project_id) .order_by(ProjectChat.time_stamp.desc()) .paginate(page, per_page, True) ) dto = ProjectChatDTO() if project_messages.total == 0: return dto for message in project_messages.items: chat_dto = ChatMessageDTO() chat_dto.message = message.message chat_dto.username = message.posted_by.username chat_dto.picture_url = message.posted_by.picture_url chat_dto.timestamp = message.time_stamp dto.chat.append(chat_dto) dto.pagination = Pagination(project_messages) return dto
class Restriction(db.Model): id = db.Column(db.Integer, primary_key=True) amount = db.Column(db.Integer, nullable=True) transaction = db.Column(db.Integer, nullable=True) primary_location = db.Column(db.String(127), nullable=True) distance = db.Column(db.Integer, nullable=True) cat_id = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) isActive = db.Column(db.Boolean, nullable=False, default=True)
class Url(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.String(40), index=True, unique=True) url = db.Column(db.String(256), index=False, unique=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) newsletter_id = db.Column(db.Integer, db.ForeignKey('newsletter.id')) def __repr__(self): return '<UUID %r URL %r>'.format(self.uuid, self.url)
class CourseSections(db.Model): __tablename__ = 'course_sections' id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(20)) name = db.Column(db.String(50)) course_id = db.Column(db.Integer, db.ForeignKey('courses.id')) teacher_id = db.Column(db.Integer, db.ForeignKey('users.id')) course_section_period = db.Column(db.String(6)) section_times = db.relationship("SectionTimes", backref='course_section', lazy='dynamic')
class CoachExercise(db.Model): __tablename__ = "Coach_exercises" id = db.Column(db.Integer, primary_key=True) # 1 to 1 relationship with Exercises exercise_id = db.Column(db.Integer, db.ForeignKey('Exercises.id'), nullable=False) category = db.relationship(Exercise, lazy=True, uselist=False, single_parent=True, primaryjoin="Exercise.id==CoachExercise.exercise_id") name = db.relationship(Exercise, lazy=True, uselist=False, single_parent=True, primaryjoin="Exercise.id==CoachExercise.exercise_id") # many to 1 relationship with Coach_sessions table coach_session_id = db.Column(db.Integer, db.ForeignKey('Coach_sessions.id'), nullable=False) order = db.Column(db.Integer, nullable=False)
class BillDetail(db.Model): __tablename__ = 'billdetail' id = db.Column(db.Integer, primary_key=True, autoincrement=True) bill_id = db.Column(db.Integer, db.ForeignKey('billheader.id'), nullable=False) bill = relationship("BillHeader") products_id = db.Column(db.ForeignKey('products.id'), nullable=False) products = relationship("Products") unitprice = db.Column(db.Integer) quantity = db.Column(db.Integer)
class Habit(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(127), nullable=False) curr_num = db.Column(db.Float, nullable=False) init_num = db.Column(db.Float, nullable=False) pref_level = db.Column(db.Integer, nullable=False) change_index = db.Column(db.Float, nullable=False) curr_target = db.Column(db.Integer, nullable=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) cat_id = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=False)
class Expense(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(127), nullable=False) amount = db.Column(db.Integer, nullable=False, default=0) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) cat_id = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=False) isProcessable = db.Column(db.Boolean, nullable=False, default=False) def __repr__(self): return f"{self.id}"
class Subscribed(db.Model): user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, primary_key=True) post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), nullable=False, primary_key=True) def __repr__(self): return f"Subscribed('{self.user_id}','{self.post_id}')"