2019-10-24 06:36:01 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2023-02-22 12:30:43 +00:00
|
|
|
from django.db.models import Count
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2019-10-24 06:36:01 +00:00
|
|
|
|
2023-02-22 12:30:43 +00:00
|
|
|
from common.serializers.mixin import ObjectRelatedField
|
2019-10-24 06:36:01 +00:00
|
|
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
|
|
|
from .. import utils
|
2023-02-22 12:30:43 +00:00
|
|
|
from ..models import User, UserGroup
|
2019-10-24 06:36:01 +00:00
|
|
|
|
|
|
|
__all__ = [
|
2019-12-16 08:53:29 +00:00
|
|
|
'UserGroupSerializer',
|
2019-10-24 06:36:01 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
class UserGroupSerializer(BulkOrgResourceModelSerializer):
|
2023-02-22 12:30:43 +00:00
|
|
|
users = ObjectRelatedField(
|
2019-12-16 08:53:29 +00:00
|
|
|
required=False, many=True, queryset=User.objects, label=_('User'),
|
2019-10-24 06:36:01 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = UserGroup
|
2020-04-29 08:01:14 +00:00
|
|
|
fields_mini = ['id', 'name']
|
|
|
|
fields_small = fields_mini + [
|
|
|
|
'comment', 'date_created', 'created_by'
|
|
|
|
]
|
2023-06-14 06:48:50 +00:00
|
|
|
fields = fields_mini + fields_small + ['users']
|
2019-10-24 06:36:01 +00:00
|
|
|
extra_kwargs = {
|
2020-11-11 02:27:18 +00:00
|
|
|
'created_by': {'label': _('Created by'), 'read_only': True},
|
|
|
|
'users_amount': {'label': _('Users amount')},
|
|
|
|
'id': {'label': _('ID')},
|
2019-10-24 06:36:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.set_fields_queryset()
|
|
|
|
|
|
|
|
def set_fields_queryset(self):
|
2020-04-30 08:58:08 +00:00
|
|
|
users_field = self.fields.get('users')
|
|
|
|
if users_field:
|
2020-07-08 07:17:07 +00:00
|
|
|
users_field.child_relation.queryset = utils.get_current_org_members()
|
2019-10-24 06:36:01 +00:00
|
|
|
|
2019-12-16 08:53:29 +00:00
|
|
|
@classmethod
|
|
|
|
def setup_eager_loading(cls, queryset):
|
|
|
|
""" Perform necessary eager loading of data. """
|
2022-08-24 11:32:49 +00:00
|
|
|
queryset = queryset.prefetch_related('users').annotate(users_amount=Count('users'))
|
2019-12-16 08:53:29 +00:00
|
|
|
return queryset
|