2018-02-07 15:25:15 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2022-12-07 10:58:57 +00:00
|
|
|
from django.db.models import Count
|
2021-03-11 12:09:23 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2022-12-07 10:58:57 +00:00
|
|
|
from rest_framework import serializers
|
2019-04-25 02:11:50 +00:00
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
2018-02-07 15:25:15 +00:00
|
|
|
from ..models import Label
|
|
|
|
|
|
|
|
|
2019-06-19 08:45:14 +00:00
|
|
|
class LabelSerializer(BulkOrgResourceModelSerializer):
|
2022-12-07 10:58:57 +00:00
|
|
|
asset_count = serializers.ReadOnlyField(label=_("Assets amount"))
|
2018-02-07 15:25:15 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = Label
|
2021-04-29 11:10:45 +00:00
|
|
|
fields_mini = ['id', 'name']
|
|
|
|
fields_small = fields_mini + [
|
2022-12-07 10:58:57 +00:00
|
|
|
'value', 'category', 'is_active',
|
|
|
|
'date_created', 'comment',
|
2019-07-11 10:44:16 +00:00
|
|
|
]
|
2021-04-29 11:10:45 +00:00
|
|
|
fields_m2m = ['asset_count', 'assets']
|
|
|
|
fields = fields_small + fields_m2m
|
2019-07-11 10:44:16 +00:00
|
|
|
read_only_fields = (
|
2021-03-11 12:09:23 +00:00
|
|
|
'category', 'date_created', 'asset_count',
|
2019-07-11 10:44:16 +00:00
|
|
|
)
|
2020-06-12 03:45:03 +00:00
|
|
|
extra_kwargs = {
|
2022-03-17 11:04:39 +00:00
|
|
|
'assets': {'required': False, 'label': _('Asset')}
|
2020-06-12 03:45:03 +00:00
|
|
|
}
|
2018-02-07 15:25:15 +00:00
|
|
|
|
2022-12-07 10:58:57 +00:00
|
|
|
@classmethod
|
|
|
|
def setup_eager_loading(cls, queryset):
|
2023-02-24 06:33:37 +00:00
|
|
|
queryset = queryset.prefetch_related('assets') \
|
|
|
|
.annotate(asset_count=Count('assets'))
|
2022-12-07 10:58:57 +00:00
|
|
|
return queryset
|
2018-02-07 15:25:15 +00:00
|
|
|
|
|
|
|
|
2019-06-19 08:45:14 +00:00
|
|
|
class LabelDistinctSerializer(BulkOrgResourceModelSerializer):
|
2018-02-07 15:25:15 +00:00
|
|
|
value = serializers.SerializerMethodField()
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = Label
|
|
|
|
fields = ("name", "value")
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_value(obj):
|
|
|
|
labels = Label.objects.filter(name=obj["name"])
|
|
|
|
return ', '.join([label.value for label in labels])
|