2025-12-28 16:22:33 +01:00

27 lines
847 B
Python

from typing import TypeVar
from django.db.models import Avg
from django.db.models.functions import Coalesce
from django.db import models
T = TypeVar('T')
class PublicationQuerySet(models.QuerySet[T]):
def with_score(self):
qs = self
qs = qs.annotate(average_score=Coalesce(Avg("ratings__score"), 0.0))
return qs
def only_publish(self):
from .models import Publication
qs = self
return qs.filter(status=Publication.StatusVarioations.PUBLIC.value)
class PublicationManager(models.Manager[T]):
def get_queryset(self):
return PublicationQuerySet[T](self.model, using=self._db).with_score()
def with_related(self):
return self.get_queryset().select_related('user', 'category')
def only_publish(self):
return self.get_queryset().only_publish()