Source code for groups_api.serializers

from typing import cast

from datasets_api.permissions import get_dataset_info
from django.contrib.auth.models import Group
from rest_framework import serializers


[docs] class GroupCreateSerializer(serializers.ModelSerializer): """Serializer used for group creation.""" name = serializers.CharField(validators=[])
[docs] class Meta: # pylint: disable=too-few-public-methods model = Group fields = ("id", "name")
[docs] def create(self, validated_data: dict[str, str]) -> Group: group = Group.objects.create(name=validated_data["name"]) return group
[docs] class GroupSerializer(serializers.ModelSerializer): id = serializers.IntegerField() name = serializers.CharField(validators=[])
[docs] class Meta: # pylint: disable=too-few-public-methods model = Group fields = ("id", "name")
[docs] class GroupRetrieveSerializer(GroupSerializer): """Serializer used for group listing.""" users = serializers.SlugRelatedField( many=True, read_only=True, slug_field="email", source="user_set", ) datasets = serializers.SerializerMethodField()
[docs] class Meta: # pylint: disable=too-few-public-methods model = Group fields = ("id", "name", "users", "datasets")
[docs] def get_datasets(self, group: Group) -> list[dict]: return sorted(filter(None, [ get_dataset_info(d.dataset_id) for d in group.dataset_set.all() ]), key=lambda d: d["datasetName"].lower())
[docs] def to_representation(self, instance: Group) -> dict: response = super().to_representation(instance) response["users"] = sorted(response["users"]) return cast(dict, response)