class LatencyMetricsSerializer(Serializer): l_25 = DecimalField(max_digits=10, decimal_places=4, coerce_to_string=False) l_75 = DecimalField(max_digits=10, decimal_places=4, coerce_to_string=False) l_90 = DecimalField(max_digits=10, decimal_places=4, coerce_to_string=False) l_95 = DecimalField(max_digits=10, decimal_places=4, coerce_to_string=False) l_99 = DecimalField(max_digits=10, decimal_places=4, coerce_to_string=False) avg = DecimalField(max_digits=10, decimal_places=4, coerce_to_string=False) median = DecimalField(max_digits=10, decimal_places=4, coerce_to_string=False) max = DecimalField(max_digits=10, decimal_places=4, coerce_to_string=False) min = DecimalField(max_digits=10, decimal_places=4, coerce_to_string=False) def create(self, validated_data): return LatencyMetrics(**validated_data)
class RadioSongSerializer(ModelSerializer): ''' A song serializer that is specific to the radio DJ and the underlying audio manipulation application. ''' album = StringRelatedField() artists = StringRelatedField(many=True) game = StringRelatedField() length = DecimalField( max_digits=10, decimal_places=2, source='active_store.length' ) replaygain = CharField(source='active_store.replaygain') path = SerializerMethodField() class Meta: model = Song fields = ('album', 'artists', 'game', 'song_type', 'title', 'length', 'replaygain', 'path') def get_path(self, obj): '''Converts the IRI into a filesystem path.''' iri = str(obj.active_store.iri) if iri.startswith('file://'): return iri_to_path(iri) return iri
class OrderItemSerializer(ModelSerializer): product_name = CharField(source='product.name', read_only=True) product_price = DecimalField(max_digits=15, decimal_places=2, source='product.price', read_only=True) class Meta: model = OrderItem fields = ('product', 'quantity', 'product_name', 'product_price')
class MemoryItemSummarySerializer(Serializer): avg = DecimalField(max_digits=100, decimal_places=4, coerce_to_string=False) def create(self, validated_data): return MemoryItemSummarySerializer(**validated_data)
class LastSevenDaySalesSerializer(Serializer): sale_date = DateTimeField(required=False, read_only=True, format="%d-%m-%Y") price_total__sum = DecimalField(required=False, read_only=True, decimal_places=2, max_digits=12) distributor_margin_total__sum = DecimalField(required=False, read_only=True, decimal_places=2, max_digits=12) retailer_margin_total__sum = DecimalField(required=False, read_only=True, decimal_places=2, max_digits=12)
class ComicReaderTitleSerializer(Serializer): """Components for constructing the title.""" seriesName = CharField(read_only=True) # noqa: N815 volumeName = CharField(read_only=True) # noqa: N815 issue = DecimalField(max_digits=5, decimal_places=1, read_only=True) issueCount = IntegerField(read_only=True) # noqa: N815
class PerformanceSerializer(ModelSerializer): """ Performance Metrics Data Serializer """ def __init__(self, *args, **kwargs): super(PerformanceSerializer, self).__init__(*args, **kwargs) if 'context' in kwargs: if 'request' in kwargs['context']: fields = kwargs['context']['request'].query_params.getlist( 'field', []) excluded = kwargs['context']['request'].query_params.getlist( 'exclude', []) existing = set(self.fields.keys()) if fields: included = set(fields) for other in existing - included: self.fields.pop(other) if excluded: for field in excluded: self.fields.pop(field) date = DateField(required=False, allow_null=False) channel = CharField(required=False, allow_null=False) country = CharField(required=False, allow_null=False) os = CharField(required=False, allow_null=False) impressions = IntegerField(required=False, allow_null=False) clicks = IntegerField(required=False, allow_null=False) installs = IntegerField(required=False, allow_null=False) spend = DecimalField(required=False, max_digits=30, decimal_places=2, allow_null=False) revenue = DecimalField(required=False, max_digits=30, decimal_places=2, allow_null=False) cpi = DecimalField(required=False, max_digits=30, decimal_places=2, allow_null=False) class Meta: model = Performance fields = '__all__'
class RaingageSerializer(Serializer): id = IntegerField(read_only=True) name = CharField() code = CharField() latitude = DecimalField(max_digits=25, decimal_places=5) longitude = DecimalField(max_digits=25, decimal_places=5) def create(self, validated_data): pass def update(self, instance, validated_data): pass
class TransferMoneySerializer(Serializer): send_from = IntegerField(min_value=1) account_id = IntegerField(min_value=1) amount = DecimalField(min_value=0.01, max_digits=8, decimal_places=2) message = CharField(max_length=30) class Meta: fields = ('send_from', 'account_id', 'amount', 'message')
class DocumentSerializer(ModelSerializer): document_id = DecimalField(source='documento_id', max_digits=10, decimal_places=0, read_only=True) category_id = DecimalField(source='documento_categoria_id', max_digits=10, decimal_places=0, write_only=True) category = DocumentCategorySerializer(source='documento_categoria', read_only=True) name = CharField(max_length=200, source='documento_nombre') alias = CharField(max_length=250, source='documento_alias') downloads = IntegerField(source='documento_descargas', read_only=True) description = CharField(source='documento_descripcion') url = CharField(max_length=250, source='documento_url') lang = CharField(max_length=5, source='documento_lenguaje') nacionality = CharField(max_length=5, source='documento_nacionalidad') author = CharField(max_length=250, source='documento_autor') producer = CharField(max_length=250, source='documento_productor') director = CharField(max_length=250, source='documento_director') group = CharField(max_length=250, source='documento_agrupacion') year = IntegerField(source='documento_anio') tags = CharField(source='documento_tags') license_doc = CharField(max_length=5, source='documento_licencia') doc_type = CharField(max_length=5, source='documento_tipo') enabled = CharField(max_length=5, source='documento_habilitado') class Meta: model = XDocumento fields = ( 'document_id', 'category_id', 'category', 'name', 'alias', 'downloads', 'description', 'url', 'lang', 'nacionality', 'author', 'producer', 'director', 'group', 'year', 'tags', 'license_doc', 'doc_type', 'enabled' ) depth = 1
class BlogSerializer(Serializer): name = CharField(max_length=10, min_length=5, allow_blank=True) price = DecimalField(max_digits=8, decimal_places=2) category = IntegerField() comment = CharField() extra_name = CharField() # 自定义静态属性的返回 # article = PrimaryKeyRelatedField(read_only=True,many=True) #常用:仅仅返回外键id 加上many=True返回多个外键id 应用场景:展示列表页面,然后拿着对应的id去访问详情页面 article = ArticleSerializer(many=True) # 序列化器嵌套序列化器进行返回(前提:需要写在定义的序列化器前面)
class StudentSerializer(ModelSerializer): weeks = ListField() total = IntegerField() percent = DecimalField(max_digits=7, decimal_places=4) class Meta: model = LMSUser fields = ('id', 'fullname', 'weeks', 'total', 'percent')
class DocumentCategorySerializer(ModelSerializer): category_id = DecimalField(max_digits=10, decimal_places=0, source='documento_categoria_id') name = CharField(max_length=150, source='documento_categoria_nombre') class Meta: model = XDocumentoCategoria fields = ('category_id', 'name')
class StudentAssessmentSerializer(ModelSerializer): user_views = IntegerField() attempts = IntegerField() average_score = DecimalField(max_digits=7, decimal_places=4) class Meta: model = Page fields = ('id', 'title', 'content_type', 'user_views', 'attempts', 'average_score')
class CitySummarySerializer(Serializer): city_name = CharField(source='product__city') total_amount = DecimalField( max_digits=11, decimal_places=2, source='amount__sum') class Meta: fields = ('city_name', 'total_amount',)
class NegativeSerializer(ModelSerializer): film = FilmSerializer(many=False) lens = LensSerializer(many=False) filter = FilterSerializer(many=False) teleconverter = TeleconverterSerializer(many=False) mount_adapter = MountAdapterSerializer(many=False) exposure_program = ExposureProgramSerializer(many=False) metering_mode = MeteringModeSerializer(many=False) shutter_speed = ShutterSpeedSerializer(many=False) photographer = PersonSerializer(many=False) copyright = CharField() latitude = DecimalField(max_digits=18, decimal_places=15) longitude = DecimalField(max_digits=18, decimal_places=15) focal_length = IntegerField() class Meta: model = Negative fields = '__all__'
class PageSerializer(ModelSerializer): weeks = ListField() total = IntegerField() percent = DecimalField(max_digits=7, decimal_places=4) class Meta: model = Page fields = ('id', 'title', 'parent_id', 'content_type', 'weeks', 'total', 'percent')
class MembershipModelSerializer(ModelSerializer): price = DecimalField(write_only=True, max_digits=100, decimal_places=2) slug = SlugField(read_only=True) class Meta: model = Membership fields = ("membership_type", "slug", "price") def create(self, validated_data): return Membership.objects.create(**validated_data)
class KitProductsSerializer(Serializer): sku = CharField(max_length=200) amount = IntegerField() discount = DecimalField(max_digits=6, decimal_places=3) def validate_discount(self, value): if not 0.0 <= value <= 1.0: raise ValidationError( "The discount must be a percentage between 0 and 1.") return value
class PrecipEventSerializer(Serializer): id = IntegerField(read_only=True) event_date = DateField() event_time = TimeField() duration = DecimalField(max_digits=15, decimal_places=5) depth = DecimalField(max_digits=15, decimal_places=5) time_est = CharField() def create(self, validated_data): pass def update(self, instance, validated_data): pass
class PriceTierSerializer(ModelSerializer): resource_uri = HyperlinkedIdentityField(view_name='price-tier-detail') active = BooleanField() name = CharField() method = EnumeratedField(PAYMENT_METHOD_CHOICES) price = DecimalField(max_digits=12, decimal_places=2) class Meta: model = Price fields = ['resource_uri', 'active', 'name', 'method', 'price']
class MicrobenchmarkMetricsSerializer(Serializer): # Fields throughput = DecimalField(max_digits=34, decimal_places=15, coerce_to_string=False) tolerance = IntegerField() iterations = IntegerField() status = ChoiceField(required=False, choices=MICROBENCHMARK_STATUS_CHOICES) ref_throughput = DecimalField(required=False, max_digits=34, decimal_places=15, coerce_to_string=False) stdev_throughput = DecimalField(required=False, max_digits=34, decimal_places=15, coerce_to_string=False) def create(self, validated_data): return MicrobenchmarkMetrics(**validated_data)
class IncrementalMetricsSerializer(Serializer): # Fields time = IntegerField() throughput = DecimalField(max_digits=24, decimal_places=15, coerce_to_string=False) latency = LatencyMetricsSerializer(required=False) def create(self, validated_data): return IncrementalMetrics(**validated_data)
class PManagementSerializer(BaseAPISerializer): size = DecimalField(max_digits=12, decimal_places=3, coerce_to_string=False, required=False, allow_null=True) class Meta: model = Management exclude = []
class CallRecordSerializer(Serializer): """ Serializer that gathers information from Call Start and Call End models. """ start = DateTimeField() end = DateTimeField() call_id = CharField() destination = CharField() duration = DurationField() price = DecimalField(max_digits=10, decimal_places=2)
class OLTPBenchMetricsSerializer(Serializer): # Fields throughput = DecimalField(max_digits=24, decimal_places=15, coerce_to_string=False) latency = LatencyMetricsSerializer(required=False) incremental_metrics = IncrementalMetricsSerializer(required=False, many=True) def create(self, validated_data): return OLTPBenchMetrics(**validated_data)
class CampaignSerializer(ModelSerializer): location = JSONField() publicity_configuration = JSONField() products = JSONField() budget = DecimalField(max_digits=12, decimal_places=3) gender_range = ChoiceField(choices=['M', 'F', 'M-F']) class Meta: model = Campaign exclude = ('clients', )
class ProductSerializer(serializers.ModelSerializer): title = serializers.CharField() slug = serializers.SlugField() created_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S") updated_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S") featured_image = serializers.SerializerMethodField( 'get_featured_image_url') category = CategorySerializer(read_only=True, many=True) regular_price = DecimalField( source='price.regular_price', read_only=True, decimal_places=2, max_digits=100, ) sale_price = DecimalField( source='price.sale_price', read_only=True, decimal_places=2, max_digits=100, ) sale_start_date = DateTimeField(source='price.sale_start_date') sale_end_date = DateTimeField(source='price.sale_end_date') class Meta: model = Product fields = ('__all__') depth = 1 # fields = ('id', 'title', 'slug', 'category') # def get_single_product(self, object): # pass def get_category(self, object): category = object.category print('Test = ', category) return category def get_featured_image_url(self, object): image_url = FULL_MEDIA_URL + str(object.featured_image) return image_url
class MetadataAggregatesSerializer(Serializer): """Aggregate stats for the comics selected in the metadata dialog.""" # Aggregate Annotations size = IntegerField(read_only=True) x_cover_path = CharField(read_only=True) x_page_count = IntegerField(read_only=True) # UserBookmark annotations bookmark = IntegerField(read_only=True) finished = BooleanField(read_only=True) progress = DecimalField(max_digits=5, decimal_places=2, read_only=True)
class MonitoringLocationSerializer(ModelSerializer): """ Serializer for RegistrySerializer """ agency = AgencyLookupSerializer() country = CountryLookupSerializer() state = StateLookupSerializer() county = CountyLookupSerializer() dec_lat_va = DecimalField(None, None) dec_long_va = DecimalField(None, None) alt_va = DecimalField(None, None) altitude_units = UnitsLookupSerializer() well_depth = DecimalField(None, None) well_depth_units = UnitsLookupSerializer() nat_aqfr = NatAqfrLookupSerializer() insert_user = StringRelatedField() update_user = StringRelatedField() class Meta: model = MonitoringLocation fields = '__all__'