6
0

Collection.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from __future__ import annotations
  2. from typing import List
  3. from pycs import db
  4. from pycs.database.base import NamedBaseModel
  5. class Collection(NamedBaseModel):
  6. """ DB Model for collections """
  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. # pylint: disable=import-outside-toplevel
  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.files.count() == 0:
  53. collection.autoselect = False
  54. found = True
  55. return collections