Collection.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from __future__ import annotations
  2. from contextlib import closing
  3. from typing import List
  4. from pycs import db
  5. from pycs.database.base import NamedBaseModel
  6. class Collection(NamedBaseModel):
  7. # table columns
  8. project_id = db.Column(
  9. db.Integer,
  10. db.ForeignKey("project.id", ondelete="CASCADE"),
  11. nullable=False)
  12. reference = db.Column(
  13. db.String, nullable=False)
  14. description = db.Column(
  15. db.String)
  16. position = db.Column(
  17. db.Integer, nullable=False)
  18. autoselect = db.Column(
  19. db.Boolean, nullable=False)
  20. # contraints
  21. __table_args__ = (
  22. db.UniqueConstraint('project_id', 'reference'),
  23. )
  24. # relationships to other models
  25. files = db.relationship("File", backref="collection", lazy="dynamic")
  26. serialize_only = NamedBaseModel.serialize_only + (
  27. "project_id",
  28. "reference",
  29. "description",
  30. "position",
  31. "autoselect",
  32. )
  33. def get_files(self, offset: int = 0, limit: int = -1):
  34. """
  35. get an iterator of files associated with this project
  36. :param offset: file offset
  37. :param limit: file limit
  38. :return: iterator of files
  39. """
  40. from pycs.database.File import File
  41. return self.files.order_by(File.id).offset(offset).limit(limit)
  42. @staticmethod
  43. def update_autoselect(collections: List[Collection]) -> List[Collection]:
  44. """ disable autoselect if there are no elements in the collection """
  45. found = False
  46. for collection in collections:
  47. if not collection.autoselect:
  48. continue
  49. if found:
  50. collection.autoselect = False
  51. elif collection.files.count() == 0:
  52. collection.autoselect = False
  53. found = True
  54. return collections