示例#1
0
class LanguageSerializer(serializers.ModelSerializer):
    name = serializers.CharField(required=False,
                                 max_length=LANGUAGE_NAME_LENGTH)
    web_url = AbsoluteURLField(source="get_absolute_url", read_only=True)
    plural = LanguagePluralSerializer(required=False)
    aliases = serializers.ListField(source="get_aliases_names", read_only=True)
    statistics_url = serializers.HyperlinkedIdentityField(
        view_name="api:language-statistics", lookup_field="code")

    class Meta:
        model = Language
        fields = (
            "code",
            "name",
            "plural",
            "aliases",
            "direction",
            "web_url",
            "url",
            "statistics_url",
        )
        extra_kwargs = {
            "url": {
                "view_name": "api:language-detail",
                "lookup_field": "code"
            },
            "code": {
                "validators": []
            },
        }

    @property
    def is_source_language(self):
        return (isinstance(self.parent, ComponentSerializer)
                and self.field_name == "source_language")

    def validate_code(self, value):
        check_query = Language.objects.filter(code=value)
        if not check_query.exists() and self.is_source_language:
            raise serializers.ValidationError(
                "Language with this language code was not found.")
        return value

    def validate_plural(self, value):
        if not value and not self.is_source_language:
            raise serializers.ValidationError("This field is required.")
        return value

    def validate_name(self, value):
        if not value and not self.is_source_language:
            raise serializers.ValidationError("This field is required.")
        return value

    def create(self, validated_data):
        plural_validated = validated_data.pop("plural", None)
        if not plural_validated:
            raise serializers.ValidationError(
                "No valid plural data was provided.")

        check_query = Language.objects.filter(code=validated_data.get("code"))
        if check_query.exists():
            raise serializers.ValidationError(
                "Language with this Language code already exists.")
        language = super().create(validated_data)
        plural = Plural(language=language, **plural_validated)
        plural.save()
        return language

    def get_value(self, dictionary):
        if self.is_source_language and "source_language" in dictionary:
            value = dictionary["source_language"]
            if isinstance(value, str):
                return {"code": value}
        return super().get_value(dictionary)
示例#2
0
class DataPieSetSerializer(serializers.Serializer):
    label = serializers.CharField()
    backgroundColor = serializers.ListField(child=serializers.CharField(
        required=False))
    data = serializers.ListField(child=serializers.IntegerField())
    fill = serializers.BooleanField(default=False, required=False)
示例#3
0
class OptionScaleSerializer(serializers.Serializer):
    xAxes = serializers.ListField(child=ScaleSerializer(), required=False)
    yAxes = serializers.ListField(child=ScaleSerializer(), required=False)
示例#4
0
class AlertRuleSerializer(CamelSnakeModelSerializer):
    """
    Serializer for creating/updating an alert rule. Required context:
     - `organization`: The organization related to this alert rule.
     - `access`: An access object (from `request.access`)
    """

    environment = serializers.ListField(child=EnvironmentField(), required=False)
    # TODO: These might be slow for many projects, since it will query for each
    # individually. If we find this to be a problem then we can look into batching.
    projects = serializers.ListField(child=ProjectField(), required=False)
    excluded_projects = serializers.ListField(child=ProjectField(), required=False)
    triggers = serializers.ListField(required=True)

    class Meta:
        model = AlertRule
        fields = [
            "name",
            "query",
            "time_window",
            "environment",
            "threshold_period",
            "aggregation",
            "projects",
            "include_all_projects",
            "excluded_projects",
            "triggers",
        ]
        extra_kwargs = {
            "query": {"allow_blank": True, "required": True},
            "threshold_period": {"default": 1, "min_value": 1, "max_value": 20},
            "time_window": {
                "min_value": 1,
                "max_value": int(timedelta(days=1).total_seconds() / 60),
                "required": True,
            },
            "aggregation": {"required": False},
            "name": {"min_length": 1, "max_length": 64},
            "include_all_projects": {"default": False},
        }

    def validate_aggregation(self, aggregation):
        try:
            return QueryAggregations(aggregation)
        except ValueError:
            raise serializers.ValidationError(
                "Invalid aggregation, valid values are %s"
                % [item.value for item in QueryAggregations]
            )

    def validate(self, data):
        """Performs validation on an alert rule's data
        This includes ensuring there is either 1 or 2 triggers, which each have actions, and have proper thresholds set.
        The critical trigger should both alert and resolve 'after' the warning trigger (whether that means > or < the value depends on threshold type).
        """
        triggers = data.get("triggers", [])
        if triggers:
            if len(triggers) == 1:
                critical = triggers[0]
                if critical.get("label", None) != CRITICAL_TRIGGER_LABEL:
                    raise serializers.ValidationError(
                        'First trigger must be labeled "%s"' % (CRITICAL_TRIGGER_LABEL)
                    )
                if critical["threshold_type"] == AlertRuleThresholdType.ABOVE.value:
                    alert_op, trigger_error = (
                        operator.lt,
                        "alert threshold must be above resolution threshold",
                    )
                elif critical["threshold_type"] == AlertRuleThresholdType.BELOW.value:
                    alert_op, trigger_error = (
                        operator.gt,
                        "alert threshold must be below resolution threshold",
                    )
                if critical["resolve_threshold"] is not None:
                    if alert_op(critical["alert_threshold"], critical["resolve_threshold"]):
                        raise serializers.ValidationError("Critical " + trigger_error)
            elif len(triggers) == 2:
                critical = triggers[0]
                warning = triggers[1]
                if (
                    critical.get("label", None) != CRITICAL_TRIGGER_LABEL
                    or warning["label"] != WARNING_TRIGGER_LABEL
                ):
                    raise serializers.ValidationError(
                        'First trigger must be labeled "%s", second trigger must be labeled "%s"'
                        % (CRITICAL_TRIGGER_LABEL, WARNING_TRIGGER_LABEL)
                    )
                else:
                    if critical["threshold_type"] != warning["threshold_type"]:
                        raise serializers.ValidationError(
                            "Must have matching threshold types (i.e. critical and warning triggers must both be an upper or lower bound)"
                        )

                    if critical["threshold_type"] == AlertRuleThresholdType.ABOVE.value:
                        alert_op, resolve_op = operator.lt, operator.lt
                        alert_error = (
                            "Critical trigger must have an alert threshold above warning trigger"
                        )
                        resolve_error = "Critical trigger must have a resolution threshold above (or equal to) warning trigger"
                        trigger_error = "alert threshold must be above resolution threshold"
                    elif critical["threshold_type"] == AlertRuleThresholdType.BELOW.value:
                        alert_op, resolve_op = operator.gt, operator.gt
                        alert_error = (
                            "Critical trigger must have an alert threshold below warning trigger"
                        )
                        resolve_error = "Critical trigger must have a resolution threshold below (or equal to) warning trigger"
                        trigger_error = "alert threshold must be below resolution threshold"
                    else:
                        raise serializers.ValidationError(
                            "Invalid threshold type. Valid values are %s"
                            % [item.value for item in AlertRuleThresholdType]
                        )

                    if alert_op(critical["alert_threshold"], warning["alert_threshold"]):
                        raise serializers.ValidationError(alert_error)
                    elif resolve_op(critical["resolve_threshold"], warning["resolve_threshold"]):
                        raise serializers.ValidationError(resolve_error)

                    if critical["resolve_threshold"] is not None:
                        if alert_op(critical["alert_threshold"], critical["resolve_threshold"]):
                            raise serializers.ValidationError("Critical " + trigger_error)

                    if warning["resolve_threshold"] is not None:
                        if alert_op(warning["alert_threshold"], warning["resolve_threshold"]):
                            raise serializers.ValidationError("Warning " + trigger_error)
            else:
                raise serializers.ValidationError(
                    "Must send 1 or 2 triggers - A critical trigger, and an optional warning trigger"
                )

            # Triggers have passed checks. Check that all triggers have at least one action now.
            for trigger in triggers:
                actions = trigger.get("actions", [])
                if actions == []:
                    raise serializers.ValidationError(
                        '"' + trigger["label"] + '" trigger must have an action.'
                    )
        else:
            raise serializers.ValidationError("Must include at least one trigger")

        return data

    def create(self, validated_data):
        try:
            triggers = validated_data.pop("triggers")
            alert_rule = create_alert_rule(
                organization=self.context["organization"], **validated_data
            )
            self._handle_trigger_updates(alert_rule, triggers)
            return alert_rule
        except AlertRuleNameAlreadyUsedError:
            raise serializers.ValidationError("This name is already in use for this project")

    def update(self, instance, validated_data):
        triggers = validated_data.pop("triggers")
        if "id" in validated_data:
            validated_data.pop("id")
        try:
            alert_rule = update_alert_rule(instance, **validated_data)
            self._handle_trigger_updates(alert_rule, triggers)
            return alert_rule
        except AlertRuleNameAlreadyUsedError:
            raise serializers.ValidationError("This name is already in use for this project")

    def _handle_trigger_updates(self, alert_rule, triggers):
        if triggers is not None:
            # Delete triggers we don't have present in the incoming data
            trigger_ids = [x["id"] for x in triggers if "id" in x]
            triggers_to_delete = AlertRuleTrigger.objects.filter(alert_rule=alert_rule).exclude(
                id__in=trigger_ids
            )
            for trigger in triggers_to_delete:
                delete_alert_rule_trigger(trigger)

            for trigger_data in triggers:
                if "id" in trigger_data:
                    trigger_instance = AlertRuleTrigger.objects.get(
                        alert_rule=alert_rule, id=trigger_data["id"]
                    )
                else:
                    trigger_instance = None

                trigger_serializer = AlertRuleTriggerSerializer(
                    context={
                        "alert_rule": alert_rule,
                        "organization": self.context["organization"],
                        "access": self.context["access"],
                    },
                    instance=trigger_instance,
                    data=trigger_data,
                )

                if trigger_serializer.is_valid():
                    trigger_serializer.save()
                else:
                    raise serializers.ValidationError(trigger_serializer.errors)
示例#5
0
class QuarterlySerializer(QuarterlyMeasurementSerializer):
    measurements = serializers.ListField(default=[])

    class Meta:
        model = QuarterlyMeasurement
        fields = ('id', 'measurements')
示例#6
0
class ServiceListSerializer(serializers.Serializer):
    list = serializers.ListField(child=ServiceSerializer())
示例#7
0
class ResumeSerializer(serializers.Serializer):
    user = serializers.IntegerField(required=True, )
    firstname = serializers.CharField(max_length=20, required=True)
    lastname = serializers.CharField(max_length=20, required=True)
    middlename = serializers.CharField(max_length=20, required=False)
    birthday = serializers.DateField(format="%d-%m-%Y",
                                     input_formats=['%d-%m-%Y', 'iso-8601'],
                                     required=True)
    phone_number = serializers.CharField(max_length=20, required=True)
    category = serializers.ListField(required=True, )
    position_name = serializers.CharField(max_length=200, required=True)
    schedule = serializers.IntegerField(required=True, )
    experience = serializers.IntegerField(required=True, )
    gender = serializers.CharField(required=True, )
    languages = serializers.ListField(required=True, )
    status = serializers.IntegerField(required=True, )
    region = serializers.IntegerField(required=True, )
    file = serializers.IntegerField(required=True, )
    district = serializers.IntegerField(required=True, )
    salary = salaryField()

    def __init__(self, *args, **kwargs):
        self.resume_id = kwargs.pop('resume')
        self.district_obj = None
        self.region_obj = None
        self.status_obj = None
        self.user_obj = None
        self.experience_obj = None
        self.schedule_obj = None
        self.file_obj = None
        self.categories = []
        self.languages_objs = []
        super(ResumeSerializer, self).__init__(*args, **kwargs)

    def validate(self, attrs):
        if self.resume_id:
            try:
                resume_model = Resume.objects.get(id=self.resume_id)
            except Resume.DoesNotExist:
                raise serializers.ValidationError(
                    {'resume': ['resume not found']})
        else:
            resume_model = Resume()

        attrs['district'] = district = attrs.get('district',
                                                 resume_model.district_id)
        attrs['region'] = region = attrs.get('region', resume_model.region_id)
        attrs['file'] = files = attrs.get('file', resume_model.files_id)
        attrs['status'] = status = attrs.get('status', resume_model.status_id)
        attrs['user'] = user = attrs.get('user', resume_model.user_id)
        attrs['experience'] = experience = attrs.get(
            'experience', resume_model.experience_id)
        attrs['schedule'] = schedule = attrs.get('schedule',
                                                 resume_model.schedule_id)
        categories = attrs.get('category', [])
        languages_objs = attrs.get('languages', [])
        if district:
            try:
                self.district_obj = District.objects.get(id=district)
            except District.DoesNotExist:
                raise serializers.ValidationError(
                    {'district': ['district not found']})
        if region:
            try:
                self.region_obj = Region.objects.get(id=region)
            except Region.DoesNotExist:
                raise serializers.ValidationError(
                    {'region': ['district not found']})
        if status:
            try:
                self.status_obj = Statuses.objects.get(id=status)
            except Statuses.DoesNotExist:
                raise serializers.ValidationError(
                    {'status': ['status not found']})

        if files:
            try:
                self.file_obj = Files.objects.get(id=files)
            except Files.DoesNotExist:
                raise serializers.ValidationError({'file': ['file not found']})

        if user:
            try:
                self.user_obj = Users.objects.get(id=user)
            except Users.DoesNotExist:
                raise serializers.ValidationError({'user': ['User not found']})
        if experience:
            try:
                self.experience_obj = Experience.objects.get(id=experience)
            except Experience.DoesNotExist:
                raise serializers.ValidationError(
                    {'experience': ['Experience not found']})

        if schedule:
            try:
                self.schedule_obj = Schedules.objects.get(id=schedule)
            except Schedules.DoesNotExist:
                raise serializers.ValidationError(
                    {'schedule': ['Schedules not found']})

        try:
            for data in categories:
                self.categories.append(Category.objects.get(pk=data))
        except Category.DoesNotExist:
            raise serializers.ValidationError(
                {'categories': ['invalid categories']})

        try:
            for data in languages_objs:
                self.languages_objs.append(Languages.objects.get(pk=data))
        except Languages.DoesNotExist:
            raise serializers.ValidationError(
                {'languages': ['invalid languages']})
        return attrs

    def save(self):
        if self.resume_id:
            try:
                resume_model = Resume.objects.get(id=self.resume_id)
            except Resume.DoesNotExist:
                raise serializers.ValidationError(
                    {'resume': ['resume not found']})
        else:
            resume_model = Resume()
        firstname = self.validated_data.get('firstname',
                                            resume_model.firstname)
        lastname = self.validated_data.get('lastname', resume_model.lastname)
        middlename = self.validated_data.get('middlename',
                                             resume_model.middlename)
        birthday = self.validated_data.get('birthday', resume_model.birthday)
        phone_number = self.validated_data.get('phone_number',
                                               resume_model.phone_number)
        position_name = self.validated_data.get('position_name',
                                                resume_model.position_name)
        salary = self.validated_data.get('salary', resume_model.salary)
        genders = self.validated_data.get('gender', None)
        manager = ResumeManager()

        if self.resume_id:
            resume = manager.updateResume(
                resume_model, self.user_obj, firstname, lastname, middlename,
                birthday, phone_number, position_name, self.categories,
                self.schedule_obj, self.experience_obj, self.region_obj,
                self.district_obj, salary, genders, self.languages_objs,
                self.status_obj, self.file_obj)
        else:
            resume = manager.createResume(
                self.user_obj, firstname, lastname, middlename, birthday,
                phone_number, position_name, self.categories,
                self.schedule_obj, self.experience_obj, self.region_obj,
                self.district_obj, salary, genders, self.languages_objs,
                self.status_obj, self.file_obj)

        return resume
示例#8
0
class MalwareUploadSerializer(ObjectSerializer):
    """MalwareUploadSerializer"""
    model = Malware

    extractor = serializers.CharField(max_length=255, required=False, label="Extractor", help_text="which Extractor implementation to use (auto: Auto-detect; none: No Extractor)")
    tag_list = serializers.CharField(max_length=1000, required=False, label="Tags", help_text="comma separated, all lowercase, no spaces")
    archive_pass = serializers.CharField(max_length=255, required=False, label="Password", help_text="archive extract password")
    store_archive = serializers.CharField(max_length=100, required=False, label="Store Archive", help_text="store or discard archive after extract")
    note_title = serializers.CharField(max_length=100, required=False, label="Note Title", help_text="title of note to be added")
    note_body = serializers.CharField(max_length=1000, required=False, label="Note Body", help_text="body to note to be added ")
    parent_hash = serializers.CharField(max_length=64, required=False, label="Parent hash", help_text="SHA256 of file to set as parent")

    # allow multiple files
    file = serializers.ListField(child=serializers.FileField(max_length=255, required=True, allow_empty_file=False))
    file_name = serializers.CharField(max_length=255, required=False, label="File Name", help_text="override file name of uploaded file")

    def validate(self, data):
        if len(data.get("file", None)) > 1 and data.get("file_name", None):
            raise serializers.ValidationError("can not provide file_name when uploading multiple files")
        return data

    def validate_file_name(self, value):
        print("File Name: {} ({})".format(value, type(value)))
        return value

    def validate_file(self, value):
        print("File: {} ({})".format(value, type(value)))
        return value

    def validate_extractor(self, value):
        # convert "none"/"false" strings into Python None
        if value in ["none", "None", "NONE", "false", "False", "FALSE"]:
            return None

        # auto detect is a valid option
        if value in ["auto", "Auto", "AUTO"]:
            return "auto"

        # if neither none nor auto then check whether selected Extractor is supported/available
        extractors = (Extractor().extractors)
        if value not in extractors:
            raise serializers.ValidationError("{}: not in list of supported Extractors: {}".format(value, extractors))

        return value

    def validate_store_archive(self, value):
        if value.lower() == "true":
            return True
        elif value.lower() == "false":
            return False
        else:
            raise serializers.ValidationError("must be either true or false")

    # tag_list expects a comma separated list of tags (tags are always all lowercase)
    def validate_tag_list(self, value):
        if not value == value.lower():
            raise serializers.ValidationError("has to be all lower case")
        if " " in value:
            raise serializers.ValidationError("spaces are not allowed")
        tag_list = value.strip().split(",")
        return tag_list

    def create(self, validated_data):
        pass
class ImageSerializer(serializers.ModelSerializer):
    caption = CaptionSerializer(required=False)
    uploader = LimitedUserSerializer(allow_null=True)
    collections = CollectionSerializer(read_only=True, many=True)
    collection_ids = serializers.ListField(
        required=False,
        write_only=True,
        child=serializers.IntegerField(min_value=0),
        allow_empty=True)
    comments_count = serializers.SerializerMethodField(read_only=True)
    image = serializers.SerializerMethodField(read_only=True)
    report = ImageReportSerializer(required=False, write_only=True)

    class Meta:
        model = Image
        fields = '__all__'
        extra_kwargs = {
            's3_key': {
                'read_only': True,
            },
            'uuid': {
                'read_only': False,
            },
            'last_updated': {
                'read_only': True,
            },
            'uploaded_at': {
                'read_only': True,
            },
        }

    def create(self, validated_data):
        # retrieve key values
        caption = validated_data.pop('caption', None)
        collection_ids = validated_data.pop('collection_ids', None)
        uploader = validated_data.pop('uploader')
        uuid = str(validated_data['uuid'])
        type = validated_data['type']
        is_private = validated_data['is_private']
        is_profile_image = validated_data['is_profile_image']

        # generate s3 key
        filename = uuid + '.' + type
        key = generate_s3_key(is_profile_image, is_private, filename)

        # create image
        image = None
        if uploader:
            uploader = User.objects.get(id=uploader['id'])
            image = Image.objects.create(s3_key=key,
                                         uploader=uploader,
                                         **validated_data)
        else:
            uploader = User.objects.get(username="******")
            image = Image.objects.create(s3_key=key,
                                         uploader=uploader,
                                         **validated_data)

        # update user's profile image
        if is_profile_image and uploader:
            uploader.profile.image = image
            uploader.save()

        # add collections to image and create associated caption
        elif caption:
            if collection_ids:
                collections = Collection.objects.filter(id__in=collection_ids)
                image.collections.set(collections)
            Caption.objects.create(text=caption['text'],
                                   corrected_text="",
                                   image=image)

        return image

    def update(self, instance: Image, validated_data):
        # create new report, if desired
        if validated_data.get('report'):
            report = validated_data.pop('report')
            ImageReport.objects.create(image=instance, **report)

        # then, update accordingly
        return super().update(instance, validated_data)

    def get_image(self, obj: Image):
        filename = obj.title + '.' + obj.type
        return create_presigned_get(settings.AWS_MEDIA_BUCKET_NAME, obj.s3_key,
                                    filename)

    def get_comments_count(self, obj: Image):
        return obj.comments.count()
class OwnerResponseSerializer(SafeBalanceResponseSerializer):
    safes = serializers.ListField(child=EthereumAddressField())
示例#11
0
class DigitalWorkSerializer(FileSerializer):
    hash = serializers.CharField()
    encoding_urls = serializers.ListField()
    isEncoding = serializers.IntegerField()
示例#12
0
class HearingCreateUpdateSerializer(serializers.ModelSerializer,
                                    TranslatableSerializer):
    geojson = JSONField(required=False, allow_null=True)

    # this field is used only for incoming data validation, outgoing data is added manually
    # in to_representation()
    sections = serializers.ListField(child=serializers.DictField(),
                                     write_only=True)

    contact_persons = NestedPKRelatedField(
        queryset=ContactPerson.objects.all(),
        many=True,
        expanded=True,
        serializer=ContactPersonSerializer)
    labels = NestedPKRelatedField(queryset=Label.objects.all(),
                                  many=True,
                                  expanded=True,
                                  serializer=LabelSerializer)

    organization = serializers.SlugRelatedField(read_only=True,
                                                slug_field='name')

    class Meta:
        model = Hearing
        fields = [
            'title',
            'id',
            'borough',
            'force_closed',
            'published',
            'open_at',
            'close_at',
            'created_at',
            'servicemap_url',
            'sections',
            'closed',
            'geojson',
            'organization',
            'slug',
            'contact_persons',
            'labels',
        ]

    def __init__(self, *args, **kwargs):
        super(HearingCreateUpdateSerializer, self).__init__(*args, **kwargs)
        self.partial = kwargs.get('partial', False)

    def _create_or_update_sections(self,
                                   hearing,
                                   sections_data,
                                   force_create=False):
        """
        Create or update sections of a hearing

        :param hearing: The hearing
        :type hearing: democracy.models.Hearing

        :param sections_data: The list of serialized sections to create or update
        :type sections_data: list of dictionaries

        :param force_create: Boolean to force the creation of new sections despite
                             the presences of section ID.
        :type force_create: Boolean

        :return: The set of the newly created/updated sections
        :rtype: Set of democracy.models.Section
        """
        sections = set()
        for index, section_data in enumerate(sections_data):
            section_data['ordering'] = index
            pk = section_data.pop('id', None)

            serializer_params = {
                'data': section_data,
            }

            if pk and not force_create:
                try:
                    section = hearing.sections.get(id=pk)
                    serializer_params['instance'] = section
                except Section.DoesNotExist:
                    pass

            serializer = SectionCreateUpdateSerializer(**serializer_params)

            try:
                serializer.is_valid(raise_exception=True)
            except ValidationError as e:
                errors = [{} for _ in range(len(sections_data))]
                errors[index] = e.detail
                raise ValidationError({'sections': errors})

            section = serializer.save(hearing=hearing)
            sections.add(section)
        return sections

    @transaction.atomic()
    def create(self, validated_data):
        sections_data = validated_data.pop('sections')
        validated_data['organization'] = self.context[
            'request'].user.get_default_organization()
        hearing = super().create(validated_data)
        self._create_or_update_sections(hearing,
                                        sections_data,
                                        force_create=True)
        return hearing

    @transaction.atomic()
    def update(self, instance, validated_data):
        """
        Handle Hearing update and it's sections create/update/delete.

        Sections are matched by their ids:
          * If an id isn't given or it doesn't exist, create a new section (ignoring given id).
          * If a section with given id exists, update it.
          * Old sections whose ids aren't matched are (soft) deleted.
        """
        if instance.organization != self.context[
                'request'].user.get_default_organization():
            raise PermissionDenied(
                'User cannot update hearings from different organizations.')

        if self.partial:
            return super().update(instance, validated_data)

        sections_data = validated_data.pop('sections')
        hearing = super().update(instance, validated_data)
        sections = self._create_or_update_sections(hearing, sections_data)
        new_section_ids = set([section.id for section in sections])
        for section in hearing.sections.exclude(id__in=new_section_ids):
            for image in section.images.all():
                image.soft_delete()
            section.soft_delete()

        return hearing

    def validate_sections(self, data):
        if self.partial:
            raise ValidationError(
                'Sections cannot be updated by PATCHing the Hearing')

        num_of_sections = defaultdict(int)

        for section_data in data:
            num_of_sections[section_data['type']] += 1
            pk = section_data.get('id')

            if pk and self.instance and not self.instance.sections.filter(
                    pk=pk).exists():
                raise ValidationError(
                    'The Hearing does not have a section with ID %s' % pk)

        if num_of_sections[InitialSectionType.MAIN] != 1:
            raise ValidationError(
                'A hearing must have exactly one main section')

        if num_of_sections[InitialSectionType.CLOSURE_INFO] > 1:
            raise ValidationError(
                'A hearing cannot have more than one closure info sections')

        return data

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['sections'] = SectionSerializer(instance=instance.sections.all(),
                                             many=True,
                                             context=self.context).data
        return data
示例#13
0
class CopySerializer(serializers.Serializer):
    """
    A serializer for Content Copy API.
    """

    source_repo = serializers.HyperlinkedRelatedField(
        help_text=_('A URI of the repository.'),
        required=False,
        queryset=Repository.objects.all(),
        view_name='repositories-detail',
    )
    source_repo_version = NestedRelatedField(
        help_text=_('A URI of the repository version'),
        required=False,
        queryset=RepositoryVersion.objects.all(),
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
        lookup_field='number',
        view_name='versions-detail',
    )
    dest_repo = serializers.HyperlinkedRelatedField(
        help_text=_('A URI of the repository.'),
        required=True,
        queryset=Repository.objects.all(),
        view_name='repositories-detail',
    )
    types = serializers.ListField(
        help_text=_('A list of types to copy ["package", "advisory"]'),
        write_only=True,
        default=['package', 'advisory'])

    def validate(self, data):
        """
        Validate that the Serializer contains valid data.

        Set the Repository based on the RepositoryVersion if only the latter is provided.
        Set the RepositoryVersion based on the Repository if only the latter is provied.
        Convert the human-friendly names of the content types into what Pulp needs to query on.

        """
        super().validate(data)
        if hasattr(self, 'initial_data'):
            validate_unknown_fields(self.initial_data, self.fields)

        new_data = {}
        new_data.update(data)

        source_repo = data.get('source_repo')
        source_repo_version = data.get('source_repo_version')

        if not source_repo and not source_repo_version:
            raise serializers.ValidationError(
                _("Either the 'source_repo' or 'source_repo_version' need to be specified"
                  ))

        if source_repo and source_repo_version:
            raise serializers.ValidationError(
                _("Either the 'source_repo' or 'source_repo_version' need to be specified "
                  "but not both."))

        if not source_repo and source_repo_version:
            repo = {'source_repo': source_repo_version.repository}
            new_data.update(repo)

        if source_repo and not source_repo_version:
            version = RepositoryVersion.latest(source_repo)
            if version:
                repo_version = {'source_repo_version': version}
                new_data.update(repo_version)
            else:
                raise serializers.ValidationError(
                    detail=_('Repository has no version available to copy'))

        types = data.get('types')
        final_types = []

        if types:
            for t in types:
                substitution = RPM_PLUGIN_TYPE_CHOICE_MAP.get(t)
                if not substitution:
                    raise serializers.ValidationError(
                        _("'{type}' is an invalid type, please use one of {choices}"
                          .format(type=t,
                                  choices=list(
                                      RPM_PLUGIN_TYPE_CHOICE_MAP.keys()))))
                final_types.append(substitution)
            new_data.update({'types': final_types})

        return new_data
示例#14
0
class CommitSerializer(serializers.Serializer):
    commit_message = serializers.CharField()
    # Expect this to be Dict<str, List<str>>
    changes = serializers.DictField(child=serializers.ListField(
        child=serializers.CharField()))
    target_directory = serializers.CharField()
示例#15
0
class ProductSerializer(BaseProductSerializer):
    """
    Base product serializer.
    """
    FIELDS = app_settings.PRODUCT_SERIALIZER_FIELDS

    url = serializers.SerializerMethodField(read_only=True)
    add_to_cart_url = serializers.SerializerMethodField(read_only=True)
    unit_price = MoneyField()
    tax = TaxSerializer()
    is_available = serializers.SerializerMethodField(read_only=True)
    category = CategorySerializer()
    brand = BrandSerializer()
    manufacturer = ManufacturerSerializer()
    modifiers = ModifierSerializer(source='get_modifiers', many=True)
    flags = FlagSerializer(source='get_flags', many=True)
    width = MeasureField(measure=Distance)
    height = MeasureField(measure=Distance)
    depth = MeasureField(measure=Distance)
    weight = MeasureField(measure=Mass)
    attributes = serializers.DictField(source='get_attributes', read_only=True)
    attribute_choices = serializers.DictField(source='get_attribute_choices',
                                              read_only=True)
    discount_amount = MoneyField(read_only=True)
    tax_amount = MoneyField(read_only=True)
    variants = serializers.SerializerMethodField()
    variations = serializers.ListField(source='get_variations', read_only=True)
    attachments = serializers.SerializerMethodField()
    relations = RelationSerializer(source='get_relations', many=True)
    reviews = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = [
            'id',
            'name',
            'slug',
            'caption',
            'code',
            'kind',
            'url',
            'add_to_cart_url',
            'price',
            'is_available',
            'description',
            'unit_price',
            'discount',
            'tax',
            'availability',
            'category',
            'brand',
            'manufacturer',
            'discountable',
            'modifiers',
            'flags',
            'width',
            'height',
            'depth',
            'weight',
            'available_attributes',
            'group',
            'attributes',
            'attribute_choices',
            'published',
            'quantity',
            'order',
            'active',
            'created_at',
            'updated_at',
            'is_single',
            'is_group',
            'is_variant',
            'is_discounted',
            'is_taxed',
            'discount_percent',
            'tax_percent',
            'discount_amount',
            'tax_amount',
            'variants',
            'variations',
            'attachments',
            'relations',
            'reviews',
        ]

    def get_fields(self):
        fields = super(ProductSerializer, self).get_fields()
        overriden = self.context['request'].GET.get('fields', None)
        names = [x for x in overriden.split(',') if x in self.Meta.fields
                 ] if overriden is not None else self.FIELDS
        names = list(set(names + self.get_included_fields()))
        for excluded in [x for x in fields if x not in names]:
            del fields[excluded]
        return fields

    def get_included_fields(self):
        return [
            x
            for x in self.context['request'].GET.get('include', '').split(',')
            if x in self.Meta.fields
        ]

    def get_url(self, obj):
        url = obj.get_absolute_url()
        return self.context['request'].build_absolute_uri(url) if url else None

    def get_add_to_cart_url(self, obj):
        try:
            url = reverse(
                'shopit-add-to-cart',
                args=[obj.safe_translation_getter('slug', any_language=True)])
            return self.context['request'].build_absolute_uri(url)
        except NoReverseMatch:
            return None

    def get_is_available(self, obj):
        return obj.is_available(request=self.context['request'])

    def get_variants(self, obj):
        variants = obj.get_variants()
        if variants:
            return ProductDetailSerializer(variants,
                                           context=self.context,
                                           many=True).data

    def get_attachments(self, obj):
        request = self.context['request']
        attachments = obj.get_attachments()
        for kind, items in [x for x in attachments.items() if x[1]]:
            for item in items:
                for key, value in item.items():
                    if key.startswith('url'):
                        item[key] = request.build_absolute_uri(value)
        return attachments

    def get_reviews(self, obj):
        reviews = obj.get_reviews(
            language=self.context['request'].LANGUAGE_CODE)
        if reviews:
            return ReviewSerializer(reviews, context=self.context,
                                    many=True).data
示例#16
0
class GammaSerializer(serializers.Serializer):
    gamma_tuple = serializers.ListField(child=serializers.IntegerField(
        min_value=0, max_value=255),
                                        default=[255, 255, 255])
示例#17
0
class ProductStateSerializer(serializers.Serializer):
    stats = serializers.DictField(child=serializers.ListField(
        child=serializers.IntegerField()))
示例#18
0
class ItemSerializer(serializers.Serializer):
    """Your Custom Serializer"""
    # Gets a list of Integers
    user_ids = serializers.ListField(child=serializers.CharField())
示例#19
0
class VacancySerializer(serializers.Serializer):
    company = serializers.IntegerField(required=True, )
    category = serializers.ListField(required=True, )
    position_name = serializers.CharField(max_length=200, required=True)
    schedule = serializers.IntegerField(required=True, )
    experience = serializers.IntegerField(required=True, )
    gender = serializers.ListField(required=True, )
    languages = serializers.ListField(required=True, )
    status = serializers.IntegerField(required=True, )
    region = serializers.IntegerField(required=True, )
    file = serializers.IntegerField(required=True, )
    district = serializers.IntegerField(required=True, )
    salary = salaryField()
    age = ageField()

    def __init__(self, *args, **kwargs):
        self.vacancy_id = kwargs.pop('vacancy')
        self.district_obj = None
        self.region_obj = None
        self.status_obj = None
        self.company_obj = None
        self.experience_obj = None
        self.schedule_obj = None
        self.file_obj = None
        self.categories = []
        self.languages_objs = []
        super(VacancySerializer, self).__init__(*args, **kwargs)

    def validate(self, attrs):
        if self.vacancy_id:
            try:
                vacancy_model = Vacancies.objects.get(id=self.vacancy_id)
            except Vacancies.DoesNotExist:
                raise serializers.ValidationError(
                    {'vacancy': ['vacancy not found']})
        else:
            vacancy_model = Vacancies()

        attrs['district'] = district = attrs.get('district',
                                                 vacancy_model.district_id)
        attrs['region'] = region = attrs.get('region', vacancy_model.region_id)
        attrs['file'] = files = attrs.get('file', vacancy_model.files_id)
        attrs['status'] = status = attrs.get('status', vacancy_model.status_id)
        attrs['company'] = company = attrs.get('company',
                                               vacancy_model.company_id)
        attrs['experience'] = experience = attrs.get(
            'experience', vacancy_model.experience_id)
        attrs['schedule'] = schedule = attrs.get('schedule',
                                                 vacancy_model.schedule_id)
        categories = attrs.get('category', [])
        languages_objs = attrs.get('languages', [])
        if district:
            try:
                self.district_obj = District.objects.get(id=district)
            except District.DoesNotExist:
                raise serializers.ValidationError(
                    {'district': ['district not found']})
        if region:
            try:
                self.region_obj = Region.objects.get(id=region)
            except Region.DoesNotExist:
                raise serializers.ValidationError(
                    {'region': ['district not found']})
        if status:
            try:
                self.status_obj = Statuses.objects.get(id=status)
            except Statuses.DoesNotExist:
                raise serializers.ValidationError(
                    {'status': ['status not found']})

        if files:
            try:
                self.file_obj = Files.objects.get(id=files)
            except Files.DoesNotExist:
                raise serializers.ValidationError({'file': ['file not found']})

        if company:
            try:
                self.company_obj = Companies.objects.get(id=company)
            except Companies.DoesNotExist:
                raise serializers.ValidationError(
                    {'company': ['Company22 not found']})
        if experience:
            try:
                self.experience_obj = Experience.objects.get(id=experience)
            except Experience.DoesNotExist:
                raise serializers.ValidationError(
                    {'experience': ['Experience not found']})

        if schedule:
            try:
                self.schedule_obj = Schedules.objects.get(id=schedule)
            except Schedules.DoesNotExist:
                raise serializers.ValidationError(
                    {'schedule': ['Schedules not found']})

        try:
            for data in categories:
                self.categories.append(Category.objects.get(pk=data))
        except Category.DoesNotExist:
            raise serializers.ValidationError(
                {'categories': ['invalid categories']})

        try:
            for data in languages_objs:
                self.languages_objs.append(Languages.objects.get(pk=data))
        except Languages.DoesNotExist:
            raise serializers.ValidationError(
                {'languages': ['invalid languages']})
        return attrs

    def save(self):
        if self.vacancy_id:
            try:
                vacancy_model = Vacancies.objects.get(id=self.vacancy_id)
            except Vacancies.DoesNotExist:
                raise serializers.ValidationError(
                    {'vacancy': ['vacancy not found']})
        else:
            vacancy_model = Vacancies()
        position_name = self.validated_data.get('position_name',
                                                vacancy_model.position_name)
        salary = self.validated_data.get('salary', vacancy_model.salary)
        age = self.validated_data.get('age', vacancy_model.age)
        genders = self.validated_data.get('gender', None)
        manager = VacnacyManager()
        if self.vacancy_id:
            vacancy = manager.updateVacanvy(
                vacancy_model, self.company_obj, position_name,
                self.categories, self.schedule_obj, self.experience_obj,
                self.region_obj, self.district_obj, salary, age, genders,
                self.languages_objs, self.status_obj, self.file_obj)
        else:
            vacancy = manager.createVacanvy(
                self.company_obj, position_name, self.categories,
                self.schedule_obj, self.experience_obj, self.region_obj,
                self.district_obj, salary, age, genders, self.languages_objs,
                self.status_obj, self.file_obj)
        return vacancy
 class AttributesSerializer(serializers.Serializer):
     responses = serializers.ListField(
         child=serializers.ListField(min_length=7, max_length=7))
示例#21
0
class AlertRuleTriggerSerializer(CamelSnakeModelSerializer):
    """
    Serializer for creating/updating an alert rule trigger. Required context:
     - `alert_rule`: The alert_rule related to this trigger.
     - `organization`: The organization related to this trigger.
     - `access`: An access object (from `request.access`)
    """

    id = serializers.IntegerField(required=False)

    # TODO: These might be slow for many projects, since it will query for each
    # individually. If we find this to be a problem then we can look into batching.
    excluded_projects = serializers.ListField(child=ProjectField(), required=False)
    actions = serializers.ListField(required=True)

    class Meta:
        model = AlertRuleTrigger
        fields = [
            "id",
            "label",
            "threshold_type",
            "alert_threshold",
            "resolve_threshold",
            "excluded_projects",
            "actions",
        ]
        extra_kwargs = {"label": {"min_length": 1, "max_length": 64}}

    def validate_threshold_type(self, threshold_type):
        try:
            return AlertRuleThresholdType(threshold_type)
        except ValueError:
            raise serializers.ValidationError(
                "Invalid threshold type, valid values are %s"
                % [item.value for item in AlertRuleThresholdType]
            )

    def create(self, validated_data):
        try:
            actions = validated_data.pop("actions")
            alert_rule_trigger = create_alert_rule_trigger(
                alert_rule=self.context["alert_rule"], **validated_data
            )
            self._handle_action_updates(alert_rule_trigger, actions)

            return alert_rule_trigger
        except AlertRuleTriggerLabelAlreadyUsedError:
            raise serializers.ValidationError("This label is already in use for this alert rule")

    def update(self, instance, validated_data):
        actions = validated_data.pop("actions")
        if "id" in validated_data:
            validated_data.pop("id")
        try:
            alert_rule_trigger = update_alert_rule_trigger(instance, **validated_data)
            self._handle_action_updates(alert_rule_trigger, actions)
            return alert_rule_trigger
        except AlertRuleTriggerLabelAlreadyUsedError:
            raise serializers.ValidationError("This label is already in use for this alert rule")

    def _handle_action_updates(self, alert_rule_trigger, actions):
        if actions is not None:
            # Delete actions we don't have present in the updated data.
            action_ids = [x["id"] for x in actions if "id" in x]
            actions_to_delete = AlertRuleTriggerAction.objects.filter(
                alert_rule_trigger=alert_rule_trigger
            ).exclude(id__in=action_ids)
            for action in actions_to_delete:
                delete_alert_rule_trigger_action(action)

            for action_data in actions:
                if "integration_id" in action_data:
                    action_data["integration"] = action_data.pop("integration_id")

                if "id" in action_data:
                    action_instance = AlertRuleTriggerAction.objects.get(
                        alert_rule_trigger=alert_rule_trigger, id=action_data["id"]
                    )
                else:
                    action_instance = None

                action_serializer = AlertRuleTriggerActionSerializer(
                    context={
                        "alert_rule": alert_rule_trigger.alert_rule,
                        "trigger": alert_rule_trigger,
                        "organization": self.context["organization"],
                        "access": self.context["access"],
                    },
                    instance=action_instance,
                    data=action_data,
                )

                if action_serializer.is_valid():
                    action_serializer.save()
                else:
                    raise serializers.ValidationError(action_serializer.errors)
示例#22
0
class BookmarkSearchHighlightsSerializer(serializers.Serializer):
    url = serializers.ListField(child=serializers.CharField())
    title = serializers.ListField(child=serializers.CharField())
    description = serializers.ListField(child=serializers.CharField())
    text = serializers.ListField(child=serializers.CharField())
示例#23
0
class MeasurementSerializer(MinutelyMeasurementSerializer):
    measurements = serializers.ListField(default=[])

    class Meta:
        model = MinutelyMeasurement
        fields = ('id', 'transductor', 'measurements')
示例#24
0
class MeasurementsSerializer(serializers.Serializer):
    measurement_type = serializers.CharField()
    details = serializers.ListField(child=MeasurementDetailsSerializer())
    note = serializers.CharField(allow_blank=True)
示例#25
0
class FileUploadSerializer(S.Serializer):
    files = S.ListField(child=S.FileField(), allow_empty=True)
示例#26
0
class BillSerializer(serializers.Serializer):
    details = serializers.ListField(child=BillDetailsSerializer())
    total_price = serializers.FloatField()
    note = serializers.CharField(allow_blank=True)
示例#27
0
class DataSerializer(serializers.Serializer):
    labels = serializers.ListField(child=serializers.CharField())
    datasets = serializers.ListField(child=DataSetSerializer())
示例#28
0
class PreprintProviderSerializer(JSONAPISerializer):

    filterable_fields = frozenset([
        'allow_submissions',
        'description',
        'domain',
        'domain_redirect_enabled',
        'id',
        'name',
        'share_publish_type',
        'reviews_workflow',
        'permissions',
    ])

    name = ser.CharField(read_only=True)
    description = ser.CharField(read_only=True)
    id = ser.CharField(read_only=True, max_length=200, source='_id')
    advisory_board = ser.CharField(read_only=True)
    example = ser.CharField(read_only=True, allow_null=True)
    domain = ser.CharField(read_only=True, allow_null=False)
    domain_redirect_enabled = ser.BooleanField(read_only=True)
    footer_links = ser.CharField(read_only=True)
    share_source = ser.CharField(read_only=True)
    share_publish_type = ser.CharField(read_only=True)
    email_support = ser.CharField(read_only=True, allow_null=True)
    preprint_word = ser.CharField(read_only=True, allow_null=True)
    allow_submissions = ser.BooleanField(read_only=True)
    additional_providers = ser.ListField(read_only=True, child=ser.CharField())

    # Reviews settings are the only writable fields
    reviews_workflow = ser.ChoiceField(choices=Workflows.choices())
    reviews_comments_private = ser.BooleanField()
    reviews_comments_anonymous = ser.BooleanField()

    permissions = ser.SerializerMethodField()

    preprints = ReviewableCountsRelationshipField(
        related_view='preprint_providers:preprints-list',
        related_view_kwargs={'provider_id': '<_id>'})

    taxonomies = RelationshipField(
        related_view='preprint_providers:taxonomy-list',
        related_view_kwargs={'provider_id': '<_id>'})

    highlighted_taxonomies = RelationshipField(
        related_view='preprint_providers:highlighted-taxonomy-list',
        related_view_kwargs={'provider_id': '<_id>'})

    licenses_acceptable = RelationshipField(
        related_view='preprint_providers:license-list',
        related_view_kwargs={'provider_id': '<_id>'})

    links = LinksField({
        'self': 'get_absolute_url',
        'preprints': 'get_preprints_url',
        'external_url': 'get_external_url'
    })

    # Deprecated fields
    header_text = ShowIfVersion(ser.CharField(read_only=True, default=''),
                                min_version='2.0',
                                max_version='2.3')
    banner_path = ShowIfVersion(ser.CharField(read_only=True, default=''),
                                min_version='2.0',
                                max_version='2.3')
    logo_path = ShowIfVersion(ser.CharField(read_only=True, default=''),
                              min_version='2.0',
                              max_version='2.3')
    email_contact = ShowIfVersion(ser.CharField(read_only=True,
                                                allow_null=True),
                                  min_version='2.0',
                                  max_version='2.3')
    social_twitter = ShowIfVersion(ser.CharField(read_only=True,
                                                 allow_null=True),
                                   min_version='2.0',
                                   max_version='2.3')
    social_facebook = ShowIfVersion(ser.CharField(read_only=True,
                                                  allow_null=True),
                                    min_version='2.0',
                                    max_version='2.3')
    social_instagram = ShowIfVersion(ser.CharField(read_only=True,
                                                   allow_null=True),
                                     min_version='2.0',
                                     max_version='2.3')
    subjects_acceptable = ShowIfVersion(ser.ListField(read_only=True,
                                                      default=[]),
                                        min_version='2.0',
                                        max_version='2.4')

    class Meta:
        type_ = 'preprint_providers'

    def get_absolute_url(self, obj):
        return obj.absolute_api_v2_url

    def get_preprints_url(self, obj):
        return absolute_reverse(
            'preprint_providers:preprints-list',
            kwargs={
                'provider_id':
                obj._id,
                'version':
                self.context['request'].parser_context['kwargs']['version']
            })

    def get_external_url(self, obj):
        return obj.external_url

    def get_permissions(self, obj):
        auth = get_user_auth(self.context['request'])
        if not auth.user:
            return []
        return get_perms(auth.user, obj)

    def validate(self, data):
        required_fields = ('reviews_workflow', 'reviews_comments_private',
                           'reviews_comments_anonymous')
        for field in required_fields:
            if data.get(field) is None:
                raise ValidationError(
                    'All reviews fields must be set at once: `{}`'.format(
                        '`, `'.join(required_fields)))
        return data

    def update(self, instance, validated_data):
        instance.reviews_workflow = validated_data['reviews_workflow']
        instance.reviews_comments_private = validated_data[
            'reviews_comments_private']
        instance.reviews_comments_anonymous = validated_data[
            'reviews_comments_anonymous']
        instance.save()
        return instance
示例#29
0
class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = [
            "people_finder_id",
            "staff_sso_id",
            "email",
            "contact_email",
            "full_name",
            "first_name",
            "last_name",
            "profile_url",
            "roles",
            "formatted_roles",
            "manager_people_finder_id",
            "completion_score",
            "is_stale",
            "works_monday",
            "works_tuesday",
            "works_wednesday",
            "works_thursday",
            "works_friday",
            "works_saturday",
            "works_sunday",
            "primary_phone_number",
            "secondary_phone_number",
            "formatted_location",
            "buildings",
            "formatted_buildings",
            "city",
            "country",
            "country_name",
            "grade",
            "formatted_grade",
            "location_in_building",
            "location_other_uk",
            "location_other_overseas",
            "key_skills",
            "other_key_skills",
            "formatted_key_skills",
            "learning_and_development",
            "other_learning_and_development",
            "formatted_learning_and_development",
            "networks",
            "formatted_networks",
            "professions",
            "formatted_professions",
            "additional_responsibilities",
            "other_additional_responsibilities",
            "formatted_additional_responsibilities",
            "language_fluent",
            "language_intermediate",
            "created_at",
            "last_edited_or_confirmed_at",
            "login_count",
            "last_login_at",
            # New fields
            "legacy_sso_user_id",
            "slug",
            "manager_slug",
            "legacy_people_finder_slug",
            "photo",
            "photo_small",
        ]

    people_finder_id = serializers.IntegerField(source="pk")
    staff_sso_id = serializers.CharField(source="user.legacy_sso_user_id",
                                         default=None)
    profile_url = serializers.SerializerMethodField()
    roles = TeamMemberSerialiser(many=True, read_only=True)
    formatted_roles = serializers.ListField(child=serializers.CharField())
    manager_people_finder_id = serializers.IntegerField(source="manager_id")
    completion_score = serializers.IntegerField(source="profile_completion")
    works_monday = serializers.SerializerMethodField()
    works_tuesday = serializers.SerializerMethodField()
    works_wednesday = serializers.SerializerMethodField()
    works_thursday = serializers.SerializerMethodField()
    works_friday = serializers.SerializerMethodField()
    works_saturday = serializers.SerializerMethodField()
    works_sunday = serializers.SerializerMethodField()
    formatted_location = serializers.SerializerMethodField()
    buildings = serializers.SlugRelatedField(many=True,
                                             read_only=True,
                                             slug_field="code")
    formatted_buildings = serializers.CharField()
    city = serializers.CharField(source="town_city_or_region")
    country = serializers.SlugRelatedField(read_only=True,
                                           slug_field="iso_2_code")
    country_name = serializers.StringRelatedField(read_only=True,
                                                  source="country")
    grade = serializers.SlugRelatedField(read_only=True, slug_field="code")
    formatted_grade = serializers.StringRelatedField(read_only=True,
                                                     source="grade")
    location_other_uk = serializers.CharField(source="regional_building")
    location_other_overseas = serializers.CharField(
        source="international_building")
    key_skills = serializers.SlugRelatedField(many=True,
                                              read_only=True,
                                              slug_field="code")
    formatted_key_skills = serializers.CharField()
    learning_and_development = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        source="learning_interests",
        slug_field="code")
    other_learning_and_development = serializers.CharField(
        source="other_learning_interests")
    formatted_learning_and_development = serializers.CharField()
    networks = serializers.SlugRelatedField(many=True,
                                            read_only=True,
                                            slug_field="code")
    formatted_networks = serializers.CharField()
    professions = serializers.SlugRelatedField(many=True,
                                               read_only=True,
                                               slug_field="code")
    formatted_professions = serializers.CharField()
    additional_responsibilities = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        source="additional_roles",
        slug_field="code")
    other_additional_responsibilities = serializers.CharField(
        source="other_additional_roles")
    formatted_additional_responsibilities = serializers.CharField()
    language_fluent = serializers.CharField(source="fluent_languages")
    language_intermediate = serializers.CharField(
        source="intermediate_languages")
    last_edited_or_confirmed_at = serializers.DateTimeField(
        source="edited_or_confirmed_at")
    last_login_at = serializers.SerializerMethodField()
    # New fields
    slug = serializers.CharField()
    manager_slug = serializers.SlugRelatedField(read_only=True,
                                                source="manager",
                                                slug_field="slug")
    legacy_people_finder_slug = serializers.CharField(source="legacy_slug")

    def get_last_login_at(self, obj):
        return obj.user and obj.user.last_login

    def _workday(self, obj, code):
        if obj.workday_list:
            return code in obj.workday_list

        return False

    def get_works_monday(self, obj):
        return self._workday(obj, "mon")

    def get_works_tuesday(self, obj):
        return self._workday(obj, "tue")

    def get_works_wednesday(self, obj):
        return self._workday(obj, "wed")

    def get_works_thursday(self, obj):
        return self._workday(obj, "thu")

    def get_works_friday(self, obj):
        return self._workday(obj, "fri")

    def get_works_saturday(self, obj):
        return self._workday(obj, "sat")

    def get_works_sunday(self, obj):
        return self._workday(obj, "sun")

    def get_formatted_location(self, obj):
        parts = (
            obj.location_in_building,
            *[x.name for x in obj.buildings.all()],
            obj.town_city_or_region,
        )

        if not any(parts):
            return None

        return ", ".join(filter(None, parts))

    def get_profile_url(self, obj):
        return settings.BASE_URL + obj.get_absolute_url()
示例#30
0
class MetricsMultiSLZ(MetricsSLZBase):
    res_id_list = serializers.ListField(required=True)