Skip to content

Commit

Permalink
Add annotate_status to base collection queryset
Browse files Browse the repository at this point in the history
  • Loading branch information
gregorjerse committed Nov 25, 2024
1 parent 094a354 commit 0f14a96
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
1 change: 1 addition & 0 deletions docs/CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Added
- Add ``contributor`` field to the ``AnnotationValue`` model
- Add version of base managers without versioning support
- Add abstract base classes for annotation fields
- Add ``annotate_status`` to collection and entity queryset

Fixed
-----
Expand Down
22 changes: 20 additions & 2 deletions resolwe/flow/models/collection.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Resolwe collection model."""

from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.aggregates import ArrayAgg
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchVectorField
Expand All @@ -13,7 +14,7 @@
from resolwe.permissions.models import PermissionObject

from .annotations import AnnotationField
from .base import BaseModel
from .base import BaseModel, DataStatus
from .history_manager import HistoryMixin
from .utils import DirtyError, validate_schema

Expand All @@ -38,7 +39,24 @@ class Meta(BaseModel.Meta):
search = SearchVectorField(null=True)


class CollectionQuerySet(BaseQuerySet):
class BaseCollectionQuerySet(BaseQuerySet):
"""A base queryset used by both collection and entity."""

def annotate_status(self):
"""Annotate the queryset with status of the collections."""

priority_order = models.Case(
*[
models.When(data__status=status, then=models.Value(sort_order))
for sort_order, status in enumerate(DataStatus.sort_order())
]
)
return self.annotate(
statuses=ArrayAgg(models.F("data__status"), ordering=priority_order.asc())
).annotate(status=models.F("statuses__0"))


class CollectionQuerySet(BaseCollectionQuerySet):
"""Query set for ``Collection`` objects."""

def duplicate(self, request_user) -> BackgroundTask:
Expand Down
4 changes: 2 additions & 2 deletions resolwe/flow/models/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@
from resolwe.permissions.models import PermissionObject

from .base import BaseModel
from .collection import BaseCollection, Collection
from .collection import BaseCollection, BaseCollectionQuerySet, Collection
from .utils import DirtyError, validate_schema


class EntityQuerySet(BaseQuerySet):
class EntityQuerySet(BaseCollectionQuerySet):
"""Query set for ``Entity`` objects."""

def duplicate(self, request_user) -> BackgroundTask:
Expand Down

0 comments on commit 0f14a96

Please sign in to comment.