utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from typing import Union, Any
  2. from dataclasses import dataclass
  3. from django.db.models import Count, Avg, Case, When, Q
  4. from django.db.models import IntegerField
  5. from . import models
  6. @dataclass
  7. class StatisticsOfHumanActionsData:
  8. """ Описание структуры данных 'Статистика поступков человека' """
  9. name: str
  10. surname: str
  11. number_of_positive_actions: int
  12. number_of_neutral_actions: int
  13. number_of_negative_actions: int
  14. average_evaluation_of_action: Union[int, float]
  15. def get_statistics_of_human_actions(
  16. human_id: int
  17. ) -> StatisticsOfHumanActionsData:
  18. """ Получаем статистику поступков человека """
  19. statistics = models.Human.objects.filter(
  20. id=human_id
  21. ).values(
  22. 'name', 'surname'
  23. ).annotate(
  24. number_of_positive_actions=Count(
  25. Case(
  26. When(actions__evaluation__gt=5, then=1),
  27. output_field=IntegerField()
  28. )
  29. ),
  30. number_of_neutral_actions=Count(
  31. Case(
  32. When(actions__evaluation=5, then=1),
  33. output_field=IntegerField()
  34. )
  35. ),
  36. number_of_negative_actions=Count(
  37. Case(
  38. When(actions__evaluation__lt=5, then=1),
  39. output_field=IntegerField()
  40. )
  41. ),
  42. average_evaluation_of_action=Avg('actions__evaluation')
  43. )[0]
  44. return StatisticsOfHumanActionsData(**statistics)
  45. def get_statistics_on_married_people(city_name: str) -> Any:
  46. """ Получаем статистику по людям находящимся в браке """
  47. return models.Human.objects.filter(
  48. Q(additional_data__is_married=True) &
  49. Q(additional_data__is_unemployed__isnull=True) &
  50. Q(addresses__city__in=[city_name]) &
  51. Q(actions__evaluation__gt=6),
  52. ).distinct().count()