admin.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Copyright © 2023 Ingram Micro Inc. All rights reserved.
  2. from django.utils.translation import gettext_lazy
  3. class CQRSAdminMasterSyncMixin:
  4. """
  5. Mixin that includes a custom action in AdminModel. This action allows synchronizing
  6. master's model items from Django Admin page,
  7. """
  8. def get_actions(self, request):
  9. """
  10. Overriding method from AdminModel class; it is used to include the sync method in
  11. the actions list.
  12. """
  13. if self.actions is not None and 'sync_items' not in self.actions:
  14. self.actions = list(self.actions) + ['sync_items']
  15. return super().get_actions(request)
  16. def _cqrs_sync_queryset(self, queryset):
  17. """
  18. This function is used to adjust the QuerySet before sending the sync signal.
  19. Args:
  20. queryset (Queryset): Original queryset.
  21. Returns:
  22. (Queryset): Updated queryset.
  23. """
  24. return queryset
  25. def sync_items(self, request, queryset):
  26. """
  27. This method synchronizes selected items from the Admin Page.
  28. It is registered as a custom action in Django Admin
  29. Args:
  30. request (Request): Original request.
  31. queryset (Queryset): Original queryset.
  32. """
  33. items_not_synced = []
  34. for item in self._cqrs_sync_queryset(queryset):
  35. if not item.cqrs_sync():
  36. items_not_synced.append(item)
  37. total = len(queryset)
  38. total_w_erros = len(items_not_synced)
  39. total_sucess = total - total_w_erros
  40. self.message_user(
  41. request,
  42. f'{total_sucess} successfully synced. {total_w_erros} failed: {items_not_synced}',
  43. )
  44. sync_items.short_description = gettext_lazy(
  45. 'Synchronize selected %(verbose_name_plural)s via CQRS',
  46. )