db.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # ********************************************************************************
  4. # Copyright © 2019 jianglin
  5. # File Name: db.py
  6. # Author: jianglin
  7. # Email: mail@honmaple.com
  8. # Created: 2019-05-07 00:41:33 (CST)
  9. # Last Update: Wednesday 2019-05-08 13:21:02 (CST)
  10. # By:
  11. # Description:
  12. # ********************************************************************************
  13. from datetime import datetime
  14. from flask_maple.models import ModelMixin
  15. from flask_login import current_user
  16. from forums.api.user.db import User
  17. from forums.extension import db
  18. topic_collect = db.Table(
  19. 'topic_collect',
  20. db.Column('topic_id', db.Integer, db.ForeignKey('topics.id')),
  21. db.Column('collect_id', db.Integer, db.ForeignKey('collects.id')))
  22. collect_follower = db.Table(
  23. 'collect_follower',
  24. db.Column('collect_id', db.Integer, db.ForeignKey('collects.id')),
  25. db.Column('follower_id', db.Integer, db.ForeignKey('user.id')))
  26. class Collect(db.Model, ModelMixin):
  27. __tablename__ = 'collects'
  28. id = db.Column(db.Integer, primary_key=True)
  29. name = db.Column(db.String(32), nullable=False)
  30. description = db.Column(db.String(256), nullable=True)
  31. is_hidden = db.Column(db.Boolean, default=False)
  32. created_at = db.Column(
  33. db.DateTime, default=datetime.utcnow(), nullable=False)
  34. updated_at = db.Column(
  35. db.DateTime, default=datetime.utcnow(), onupdate=datetime.utcnow())
  36. author_id = db.Column(db.Integer,
  37. db.ForeignKey('user.id', ondelete="CASCADE"))
  38. author = db.relationship(
  39. User,
  40. backref=db.backref(
  41. 'collects', cascade='all,delete-orphan', lazy='dynamic'),
  42. lazy='joined')
  43. topics = db.relationship(
  44. 'Topic',
  45. secondary=topic_collect,
  46. backref=db.backref('collects', lazy='dynamic'),
  47. lazy='dynamic')
  48. followers = db.relationship(
  49. 'User',
  50. secondary=collect_follower,
  51. backref=db.backref('following_collects', lazy='dynamic'),
  52. lazy='dynamic')
  53. def is_followed(self, user=None):
  54. if user is None:
  55. user = current_user
  56. return db.session.query(collect_follower).filter(
  57. collect_follower.c.collect_id == self.id,
  58. collect_follower.c.follower_id == user.id).exists()
  59. def __str__(self):
  60. return self.name
  61. def __repr__(self):
  62. return "<Collect %r>" % self.name