class LateCustomizationSerializer(serializers.ModelSerializer): type = serializers.ChoiceField(choices=(("webapp", "webapp"), ("extension", "extension"))) app = relations.PrimaryKeyRelatedField(required=False, queryset=Webapp.objects) extension = relations.PrimaryKeyRelatedField(required=False, queryset=Extension.objects) carrier = SlugChoiceField(required=True, choices_dict=mkt.carriers.CARRIER_MAP) region = SlugChoiceField(required=True, choices_dict=mkt.regions.REGION_LOOKUP) class Meta: model = LateCustomizationItem def to_representation(self, obj): if obj.app is None: e = ExtensionSerializer(context=self.context) data = e.to_representation(obj.extension) data['latecustomization_id'] = obj.pk data['latecustomization_type'] = 'extension' else: a = SimpleAppSerializer(context=self.context) data = a.to_representation(obj.app) data['latecustomization_id'] = obj.pk data['latecustomization_type'] = 'webapp' return data def create(self, data): del data['type'] return serializers.ModelSerializer.create(self, data)
class PageSerializer(serializers.ModelSerializer): association = relations.PrimaryKeyRelatedField( queryset=Association.objects.all(), read_only=False) authors = relations.PrimaryKeyRelatedField(many=True, read_only=True) tags = serializers.SerializerMethodField() class Meta: model = Page # The dates are automatically set by Django on create or update. read_only_fields = ( "id", "authors", "creation_date", "last_update_date", "tags", ) fields = read_only_fields + ("association", "title", "text", "page_type") def get_tags(self, obj): return filter_tags(self.context, obj, short=False) def save(self, author, **kwargs): """Override the save method to add `author` to the authors field.""" instance = super(PageSerializer, self).save(**kwargs) instance.authors.add(author) return instance def update(self, instance, validated_data): # Prevent the changes to the association field when updating. if "association" in validated_data: validated_data.pop("association") return super(PageSerializer, self).update(instance, validated_data)
def get_fields(self): flds = {f : fields.IntegerField() for f in ["articles", "done","error"]} flds["plugin_id"] = relations.PrimaryKeyRelatedField(queryset=Plugin.objects.all()) flds[ "article__articlesets_set"] = relations.PrimaryKeyRelatedField(queryset=ArticleSet.objects.all()) flds["article__articlesets_set__project"] = relations.PrimaryKeyRelatedField(queryset=Project.objects.all()) return flds
class FeedItemSerializer(URLSerializerMixin, serializers.ModelSerializer): """ A serializer for the FeedItem class, which wraps all items that live on the feed. """ carrier = SlugChoiceField(required=False, choices_dict=mkt.carriers.CARRIER_MAP) region = SlugChoiceField(required=False, choices_dict=mkt.regions.REGION_LOOKUP) category = SlugModelChoiceField( required=False, queryset=Category.objects.filter(type=amo.ADDON_WEBAPP)) item_type = serializers.SerializerMethodField('get_item_type') # Types of objects that are allowed to be a feed item. app = SplitField(relations.PrimaryKeyRelatedField(required=False), FeedAppSerializer()) brand = SplitField(relations.PrimaryKeyRelatedField(required=False), FeedBrandSerializer()) class Meta: fields = ('app', 'brand', 'carrier', 'category', 'id', 'item_type', 'region', 'url') item_types = ( 'app', 'brand', ) model = FeedItem url_basename = 'feeditems' def validate(self, attrs): """ Ensure that at least one object type is specified. """ item_changed = any(k for k in self.Meta.item_types if k in attrs.keys()) num_defined = sum(1 for item in self.Meta.item_types if attrs.get(item)) if item_changed and num_defined != 1: message = ('A valid value for exactly one of the following ' 'parameters must be defined: %s' % ','.join(self.Meta.item_types)) raise serializers.ValidationError(message) return attrs def get_item_type(self, obj): for item_type in self.Meta.item_types: if getattr(obj, item_type): return item_type return
class FeedAppSerializer(URLSerializerMixin, serializers.ModelSerializer): app = SplitField(relations.PrimaryKeyRelatedField(required=True), AppSerializer()) description = TranslationSerializerField(required=False) preview = SplitField(relations.PrimaryKeyRelatedField(required=False), PreviewSerializer()) pullquote_attribution = TranslationSerializerField(required=False) pullquote_rating = serializers.IntegerField(required=False) pullquote_text = TranslationSerializerField(required=False) class Meta: fields = ('app', 'description', 'id', 'preview', 'pullquote_attribution', 'pullquote_rating', 'pullquote_text', 'url') model = FeedApp url_basename = 'feedapp'
class AdditionalContactSerializer(serializers.ModelSerializer): name = serializers.CharField(error_messages=PartyErrors.NAME, max_length=100) email = serializers.EmailField(error_messages=PartyErrors.EMAIL) phone_number = serializers.CharField( error_messages=PartyErrors.PHONE_NUMBER, max_length=50) details = serializers.CharField(error_messages=PartyErrors.DETAILS, max_length=256) address = serializers.CharField(error_messages=PartyErrors.ADDRESS, max_length=256) country = CountrySerializerField() type = KeyValueChoiceField(choices=PartyType.choices, required=True) organisation = relations.PrimaryKeyRelatedField( queryset=Organisation.objects.all()) class Meta: model = Party fields = ( "id", "name", "phone_number", "email", "details", "address", "country", "type", "organisation", ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if hasattr(self, "initial_data"): self.initial_data["type"] = PartyType.ADDITIONAL_CONTACT self.initial_data["organisation"] = self.context["organisation_pk"]
class VirtualServerSaveSerializer(RalphAPISaveSerializer): hypervisor = relations.PrimaryKeyRelatedField( source='parent', queryset=DCHost.objects, ) class Meta: model = VirtualServer exclude = ('parent',)
class FeedAppSerializer(URLSerializerMixin, serializers.ModelSerializer): """Thin wrappers around apps w/ metadata related to its feature in feed.""" app = SplitField(relations.PrimaryKeyRelatedField(required=True), AppSerializer()) description = TranslationSerializerField(required=False) image = CollectionImageField(source='*', view_name='feed-app-image-detail', format='png') preview = SplitField(relations.PrimaryKeyRelatedField(required=False), PreviewSerializer()) pullquote_attribution = TranslationSerializerField(required=False) pullquote_rating = serializers.IntegerField(required=False) pullquote_text = TranslationSerializerField(required=False) class Meta: fields = ('app', 'background_color', 'description', 'feedapp_type', 'id', 'image', 'preview', 'pullquote_attribution', 'pullquote_rating', 'pullquote_text', 'slug', 'url') model = FeedApp url_basename = 'feedapps'
class FeedAppSerializer(ValidateSlugMixin, URLSerializerMixin, serializers.ModelSerializer): """ A serializer for the FeedApp class, which highlights a single app and some additional metadata (e.g. a review or a screenshot). """ app = SplitField( relations.PrimaryKeyRelatedField(required=True, queryset=Webapp.objects), AppSerializer()) background_image = FeedImageField(allow_null=True) description = TranslationSerializerField(required=False) preview = SplitField( relations.PrimaryKeyRelatedField(required=False, queryset=Preview.objects), FeedPreviewESSerializer()) pullquote_rating = serializers.IntegerField(required=False, max_value=5, min_value=1) pullquote_text = TranslationSerializerField(required=False) class Meta: fields = ('app', 'background_color', 'background_image', 'color', 'created', 'description', 'id', 'preview', 'pullquote_attribution', 'pullquote_rating', 'pullquote_text', 'slug', 'type', 'url') model = FeedApp url_basename = 'feedapps' def validate(self, attrs): """ Require `pullquote_text` if `pullquote_rating` or `pullquote_attribution` are set. """ if (not attrs.get('pullquote_text') and (attrs.get('pullquote_rating') or attrs.get('pullquote_attribution'))): raise ValidationError('Pullquote text required if rating or ' 'attribution is defined.') return attrs
class FeedAppSerializer(URLSerializerMixin, serializers.ModelSerializer): """ A serializer for the FeedApp class, which highlights a single app and some additional metadata (e.g. a review or a screenshot). """ app = SplitField(relations.PrimaryKeyRelatedField(required=True), AppSerializer()) description = TranslationSerializerField(required=False) background_image = CollectionImageField( source='*', view_name='api-v2:feed-app-image-detail', format='png') preview = SplitField(relations.PrimaryKeyRelatedField(required=False), PreviewSerializer()) pullquote_rating = serializers.IntegerField(required=False) pullquote_text = TranslationSerializerField(required=False) class Meta: fields = ('app', 'background_color', 'created', 'description', 'feedapp_type', 'id', 'background_image', 'preview', 'pullquote_attribution', 'pullquote_rating', 'pullquote_text', 'slug', 'url') model = FeedApp url_basename = 'feedapps'
class ReorderSerializer(serializers.Serializer): forward = serializers.BooleanField() segment_from = relations.PrimaryKeyRelatedField(queryset=build_queryset) segment_to = relations.PrimaryKeyRelatedField(queryset=build_queryset) item = relations.PrimaryKeyRelatedField(queryset=build_queryset) def save(self): with transaction.atomic(): if self.validated_data['forward']: build_queryset.filter( **{ '{}__gte'.format(ordering_field): getattr(self.validated_data['segment_from'], ordering_field), '{}__lte'.format(ordering_field): getattr(self.validated_data['segment_to'], ordering_field) } ).update( **{ordering_field: F(ordering_field) - 1} ) build_queryset.filter( pk=self.validated_data['item'].pk ).update( **{ordering_field: getattr(self.validated_data['segment_to'], ordering_field)} ) else: build_queryset.filter( **{ '{}__gte'.format(ordering_field): getattr(self.validated_data['segment_from'], ordering_field), '{}__lte'.format(ordering_field): getattr(self.validated_data['segment_to'], ordering_field) } ).update( **{ordering_field: F(ordering_field) + 1} ) build_queryset.filter( pk=self.validated_data['item'].pk ).update( **{ordering_field: getattr(self.validated_data['segment_from'], ordering_field)} )
class RefundRequestSerializer(XtraModelSerializer): service = PKStringRelatedField(required=False, many=False, queryset=Service.objects.all()) address = relations.PrimaryKeyRelatedField(required=False, many=False, queryset=Service.objects.all()) comments = CommentEmbeddedSerializer(many=True, read_only=True) class Meta: model = RefundRequest fields = ('id', 'service', 'invoice', 'address', 'transaction_hash', 'amount_requested', 'requested_on', 'last_modified', 'text', 'resolved', 'comments') read_only_fields = ('id', 'requested_on', 'last_modified', 'comments')
class FeedItemSerializer(URLSerializerMixin, serializers.ModelSerializer): """ A serializer for the FeedItem class, which wraps all items that live on the feed. """ carrier = SlugChoiceField(required=False, choices_dict=mkt.carriers.CARRIER_MAP) region = SlugChoiceField(required=False, choices_dict=mkt.regions.REGION_LOOKUP) category = UnicodeChoiceField(required=False, choices=CATEGORY_CHOICES) item_type = serializers.SerializerMethodField('get_item_type') # Types of objects that are allowed to be a feed item. app = SplitField(relations.PrimaryKeyRelatedField(required=False), FeedAppSerializer()) brand = SplitField(relations.PrimaryKeyRelatedField(required=False), FeedBrandSerializer()) collection = SplitField(relations.PrimaryKeyRelatedField(required=False), FeedCollectionSerializer()) shelf = SplitField(relations.PrimaryKeyRelatedField(required=False), FeedShelfSerializer()) class Meta: fields = ('app', 'brand', 'carrier', 'category', 'collection', 'id', 'item_type', 'region', 'shelf', 'url') item_types = ('app', 'brand', 'collection', 'shelf',) model = FeedItem url_basename = 'feeditems' def validate(self, attrs): """ Ensure that at least one object type is specified. """ item_changed = any(k for k in self.Meta.item_types if k in attrs.keys()) num_defined = sum(1 for item in self.Meta.item_types if attrs.get(item)) if item_changed and num_defined != 1: message = ('A valid value for exactly one of the following ' 'parameters must be defined: %s' % ','.join( self.Meta.item_types)) raise serializers.ValidationError(message) return attrs def get_item_type(self, obj): for item_type in self.Meta.item_types: if getattr(obj, item_type): return item_type return def validate_shelf(self, attrs, source): """ If `shelf` is defined, validate that the FeedItem's `carrier` and `region` match the `carrier` and `region on `shelf`. """ shelf_id = attrs.get(source) if shelf_id: shelf = FeedShelf.objects.get(pk=shelf_id) carrier = CARRIER_CHOICE_DICT[shelf.carrier] if attrs.get('carrier') != carrier.slug: raise serializers.ValidationError( 'Feed item carrier does not match operator shelf carrier.') region = REGIONS_CHOICES_ID_DICT[shelf.region] if attrs.get('region') != region.slug: raise serializers.ValidationError( 'Feed item region does not match operator shelf region.') return attrs
class PartySerializer(serializers.ModelSerializer): name = serializers.CharField(error_messages=PartyErrors.NAME) address = serializers.CharField(error_messages=PartyErrors.ADDRESS) country = CountrySerializerField() website = serializers.CharField(required=False, allow_blank=True) type = serializers.ChoiceField(choices=PartyType.choices, error_messages=PartyErrors.TYPE) organisation = relations.PrimaryKeyRelatedField( queryset=Organisation.objects.all()) document = serializers.SerializerMethodField() role = KeyValueChoiceField(choices=PartyRole.choices, error_messages=PartyErrors.ROLE, required=False) role_other = serializers.CharField(max_length=75, allow_null=True, allow_blank=True, required=False, error_messages=PartyErrors.ROLE_OTHER) sub_type = KeyValueChoiceField(choices=SubType.choices, error_messages=PartyErrors.SUB_TYPE) sub_type_other = serializers.CharField( max_length=75, allow_null=True, allow_blank=True, required=False, error_messages=PartyErrors.SUB_TYPE_OTHER) flags = FlagSerializer(many=True, required=False) clearance_level = KeyValueChoiceField(choices=PvGrading.choices, allow_null=True, required=False, allow_blank=True) descriptors = serializers.CharField(allow_null=True, required=False, allow_blank=True) copy_of = relations.PrimaryKeyRelatedField(queryset=Party.objects.all(), allow_null=True, required=False) deleted_at = serializers.DateTimeField(allow_null=True, required=False) class Meta: model = Party fields = ( "id", "name", "address", "country", "website", "type", "organisation", "document", "sub_type", "sub_type_other", "role", "role_other", "flags", "copy_of", "deleted_at", "clearance_level", "descriptors", ) def __init__(self, *args, **kwargs): application_type = kwargs.pop("application_type", None) super(PartySerializer, self).__init__(*args, **kwargs) if hasattr(self, "initial_data"): party_type = kwargs.get("data", {}).get("type") role = self.initial_data.get("role") sub_type = self.initial_data.get("sub_type") if sub_type == SubType.OTHER: self.fields["sub_type_other"].required = True self.fields["sub_type_other"].allow_blank = False self.fields["sub_type_other"].allow_null = False else: self.fields.pop("sub_type_other") if application_type == CaseTypeSubTypeEnum.F680: self.fields["clearance_level"].required = True if party_type == PartyType.THIRD_PARTY: self.fields["role"].required = True if role == PartyRole.OTHER: self.fields["role_other"].required = True self.fields["role_other"].allow_blank = False self.fields["role_other"].allow_null = False else: self.fields.pop("role_other") @staticmethod def validate_website(value): """ Custom validation for URL that makes use of django URLValidator but makes the passing of http:// or https:// optional by prepending it if not given. Raises a validation error passed back to the user if invalid. Does not validate if value is empty :param value: given value for URL :return: string to save for the website field """ if value: validator = URLValidator() if "https://" not in value and "http://" not in value: # Prepend string with https:// so user doesn't have to value = f"https://{value}" validator(value) return value else: # Field is optional so doesn't validate if blank and just saves an empty string return "" def get_document(self, instance): docs = PartyDocument.objects.filter(party=instance) return docs.values()[0] if docs.exists() else None
class AlbumListSerializer(AlbumSerializer): files = relations.PrimaryKeyRelatedField(many=True)
class PkMaximalPersonSerializer(MaximalPersonSerializer): favorite_post = relations.PrimaryKeyRelatedField(null=True) liked_comments = relations.PrimaryKeyRelatedField(many=True)
class PkCommentSerializer(CommentSerializer): post = relations.PrimaryKeyRelatedField()
class PkCommentSerializer(CommentSerializer): post = relations.PrimaryKeyRelatedField(queryset=models.Post.objects)
class PkMaximalPersonSerializer(MaximalPersonSerializer): favorite_post = relations.PrimaryKeyRelatedField( required=False, queryset=models.Post.objects, **single_related_kwargs) liked_comments = relations.PrimaryKeyRelatedField( required=False, many=True, queryset=models.Comment.objects)