6
0

Collection.py 1.9 KB

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