models.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # **************************************************************************
  4. # Copyright © 2017 jianglin
  5. # File Name: models.py
  6. # Author: jianglin
  7. # Email: xiyang0807@gmail.com
  8. # Created: 2017-01-25 21:33:09 (CST)
  9. # Last Update:星期三 2017-1-25 21:33:42 (CST)
  10. # By:
  11. # Description:
  12. # **************************************************************************
  13. from forums.extension import db
  14. from sqlalchemy.ext.declarative import declared_attr
  15. from datetime import datetime
  16. from flask_maple.models import ModelMixin
  17. class CommonMixin(ModelMixin):
  18. @declared_attr
  19. def id(cls):
  20. return db.Column(db.Integer, primary_key=True)
  21. class CommonTimeMixin(CommonMixin):
  22. @declared_attr
  23. def created_at(cls):
  24. return db.Column(db.DateTime, default=datetime.utcnow())
  25. @declared_attr
  26. def updated_at(cls):
  27. return db.Column(
  28. db.DateTime, default=datetime.utcnow(), onupdate=datetime.utcnow())
  29. class CommonUserMixin(CommonTimeMixin):
  30. @declared_attr
  31. def user_id(cls):
  32. return db.Column(
  33. db.Integer, db.ForeignKey(
  34. 'user.id', ondelete="CASCADE"))
  35. @declared_attr
  36. def user(cls):
  37. name = cls.__name__.lower()
  38. if not name.endswith('s'):
  39. name = name + 's'
  40. if hasattr(cls, 'user_related_name'):
  41. name = cls.user_related_name
  42. return db.relationship(
  43. 'User',
  44. backref=db.backref(
  45. name, cascade='all,delete', lazy='dynamic'),
  46. uselist=False,
  47. lazy='joined')