class PoliceWitnessXlsxSerializer(Serializer): crid = CharField(source='allegation.crid') name = CharField(source='officer.full_name') gender = CharField(source='officer.gender_display', allow_blank=True) race = CharField(source='officer.race') appointed_date = DateField(allow_null=True, source='officer.appointed_date') resignation_date = DateField(allow_null=True, source='officer.resignation_date') rank = CharField(allow_blank=True, source='officer.rank') birth_year = IntegerField(allow_null=True, source='officer.birth_year') active = CharField(source='officer.active') complaint_percentile = FloatField(allow_null=True, source='officer.complaint_percentile') civilian_allegation_percentile = FloatField(allow_null=True, source='officer.civilian_allegation_percentile') internal_allegation_percentile = FloatField(allow_null=True, source='officer.internal_allegation_percentile') trr_percentile = FloatField(allow_null=True, source='officer.trr_percentile') honorable_mention_percentile = FloatField(allow_null=True, source='officer.honorable_mention_percentile') allegation_count = IntegerField(allow_null=True, source='officer.allegation_count') sustained_count = IntegerField(allow_null=True, source='officer.sustained_count') honorable_mention_count = IntegerField(allow_null=True, source='officer.honorable_mention_count') unsustained_count = IntegerField(allow_null=True, source='officer.unsustained_count') discipline_count = IntegerField(allow_null=True, source='officer.discipline_count') civilian_compliment_count = IntegerField(allow_null=True, source='officer.civilian_compliment_count') trr_count = IntegerField(allow_null=True, source='officer.trr_count') major_award_count = IntegerField(allow_null=True, source='officer.major_award_count') current_badge = CharField(allow_null=True, source='officer.current_badge') last_unit = CharField(allow_null=True, source='officer.last_unit.unit_name') current_salary = IntegerField(allow_null=True, source='officer.current_salary')
class AsignmentSerializer(ModelSerializer): last_end = DateField(required=False) deadline_date = DateField(read_only=True) first_report_date = DateField(read_only=True) active_goal = ReportSerializer(read_only=True) metric_info = MetricSerializer(read_only=True, source="metric") class Meta: model = Asignment fields = [ 'id', 'metric', 'metric_info', 'company', 'last_begin', 'last_end', 'days_to_deliver', 'metafreq', 'frecuency', 'periodic', 'active_goal', 'deadline_date', 'total_genetated_reports', 'reports_by_status', 'first_report_date', ]
class BulkUpdateSerializer(Serializer): room_type = ChoiceField(choices=ROOM_CHOICES, required=True) from_date = DateField(required=False) to_date = DateField(required=False) inventory = IntegerField(min_value=0, required=False) price = IntegerField(min_value=0, required=False) refine = MultipleChoiceField(choices=REFINE_CHOICES, required=False)
class SystemFactsSerializer(NotEmptySerializer): """Serializer for the SystemFacts model.""" connection_host = CharField(required=False, max_length=256) connection_port = IntegerField(required=False, min_value=0) connection_uuid = UUIDField(required=True) cpu_count = IntegerField(required=False, min_value=0) cpu_core_per_socket = IntegerField(required=False, min_value=0) cpu_siblings = IntegerField(required=False, min_value=0) cpu_hyperthreading = NullBooleanField(required=False) cpu_socket_count = IntegerField(required=False, min_value=0) cpu_core_count = IntegerField(required=False, min_value=0) date_anaconda_log = DateField(required=False) date_yum_history = DateField(required=False) etc_release_name = CharField(required=True, max_length=64) etc_release_version = CharField(required=True, max_length=64) etc_release_release = CharField(required=True, max_length=128) virt_virt = CharField(required=False, max_length=64) virt_type = CharField(required=False, max_length=64) virt_num_guests = IntegerField(required=False, min_value=0) virt_num_running_guests = IntegerField(required=False, min_value=0) virt_what_type = CharField(required=False, max_length=64) class Meta: """Meta class for SystemFactsSerializer.""" model = SystemFacts exclude = ('id', )
class OfficerAllegationXlsxSerializer(Serializer): # from allegation crid = CharField(source='allegation.crid') officer_name = CharField(allow_blank=True, source='officer.full_name') address = CharField(allow_blank=True, source='allegation.address') old_complaint_address = CharField( allow_null=True, source='allegation.old_complaint_address') incident_date = DateTimeField(format='%Y-%m-%d', allow_null=True, source='allegation.incident_date', default_timezone=pytz.utc) is_officer_complaint = BooleanField( source='allegation.is_officer_complaint') beat = CharField(source='allegation.beat.name', allow_null=True) coaccused_count = IntegerField(allow_null=True, source='allegation.coaccused_count') category = CharField(allow_null=True) subcategory = CharField(allow_null=True) start_date = DateField(allow_null=True) end_date = DateField(allow_null=True) recc_finding = CharField(allow_blank=True, source='recc_finding_display') recc_outcome = CharField(allow_blank=True) final_finding = CharField(allow_blank=True, source='final_finding_display') final_outcome = CharField(allow_blank=True) disciplined = NullBooleanField()
class OfficerXlsxSerializer(Serializer): name = CharField(source='full_name') gender = CharField(source='gender_display', allow_blank=True) race = CharField() appointed_date = DateField(allow_null=True) resignation_date = DateField(allow_null=True) rank = CharField(allow_blank=True) birth_year = IntegerField(allow_null=True) active = CharField() complaint_percentile = FloatField(allow_null=True) civilian_allegation_percentile = FloatField(allow_null=True) internal_allegation_percentile = FloatField(allow_null=True) trr_percentile = FloatField(allow_null=True) honorable_mention_percentile = FloatField(allow_null=True) allegation_count = IntegerField(allow_null=True) sustained_count = IntegerField(allow_null=True) honorable_mention_count = IntegerField(allow_null=True) unsustained_count = IntegerField(allow_null=True) discipline_count = IntegerField(allow_null=True) civilian_compliment_count = IntegerField(allow_null=True) trr_count = IntegerField(allow_null=True) major_award_count = IntegerField(allow_null=True) current_badge = CharField(allow_null=True) last_unit = CharField(allow_null=True, source='last_unit.unit_name') current_salary = IntegerField(allow_null=True)
def list_archive_dates(self, request, *args, **kwargs): dates = Post.objects.dates('created_time', 'month', order='DESC') # 独立使用序列化字段(Field) date_field = DateField() # 通过列表推导式生成一个序列化后的归档日期列表,这个列表是可被序列化的 data = [date_field.to_representation(date) for date in dates] return Response(data=data, status=status.HTTP_200_OK)
def test_with_filters(self): newer_date = timezone.now().date() older_date = newer_date - timedelta(days=1) d1 = models.Datasource.objects.create(name='d1') d2 = models.Datasource.objects.create(name='d2') c1 = models.Campaign.objects.create(name='c1') c2 = models.Campaign.objects.create(name='c2') models.DayStats.objects.create(date=older_date, datasource=d1, campaign=c1, clicks=111, impressions=222) s2 = models.DayStats.objects.create(date=newer_date, datasource=d1, campaign=c1, clicks=333, impressions=444) s3 = models.DayStats.objects.create(date=newer_date, datasource=d2, campaign=c2, clicks=555, impressions=666) response = self.client.get( self.url, { 'start_date': newer_date.strftime('%Y-%m-%d'), 'end_date': (newer_date + timedelta(days=1)).strftime('%Y-%m-%d') } ) self.assertEqual( response.status_code, status.HTTP_200_OK ) self.assertEqual( response.json(), [ { 'id': s2.id, 'date': DateField().to_representation(s2.date), 'datasource': { 'id': d1.id, 'name': d1.name }, 'campaign': { 'id': c1.id, 'name': c1.name }, 'clicks': 333, 'impressions': 444 }, { 'id': s3.id, 'date': DateField().to_representation(s3.date), 'datasource': { 'id': d2.id, 'name': d2.name }, 'campaign': { 'id': c2.id, 'name': c2.name }, 'clicks': 555, 'impressions': 666 } ] )
class LikesAnalyticsInputSerializer(Serializer): date_from = DateField(required=True) date_to = DateField(required=True) def validate(self, attrs): if attrs['date_from'] > attrs['date_to']: raise ValidationError('date_from must be <= date_to') return attrs
def list_archive_dates(self, request, *args, **kwargs): """ 获取文章归档时间列表 """ dates = Post.objects.dates('created_time', 'month', order='DESC') date_field = DateField() data = [date_field.to_representation(date)[:7] for date in dates] return Response(data=data, status=status.HTTP_200_OK)
class QueryFilterSerializer(ModelSerializer): start_time = DateField(required=False, allow_null=True) end_time = DateField(required=False, allow_null=True) status = CharField(required=False, allow_blank=True) project = CharField(required=False, allow_blank=True) def to_representation(self, instance): data = super(QueryFilterSerializer, self).to_representation(instance) data['query'] = get_object_or_404(Query, pk=data['query']).hash_code return data class Meta: model = QueryFilter fields = ('pk', 'query', 'start_time', 'end_time', 'status', 'project') read_only_fields = ('pk', 'query')
class DateRangeSerializer(Serializer): start_at = DateField() end_at = DateField() def validate(self, data): start_at = data.get("start_at", None) end_at = data.get("end_at", None) if start_at == end_at: raise ValidationError({ "start_at": [_('"Start date" must be different to "End date"')] }) return data
class WeeklyPageVisitsSerializer(Serializer): day = DateField() content_visits = IntegerField() communication_visits = IntegerField() assessment_visits = IntegerField() unique_visits = IntegerField() repeating_events = ListField()
class DailyPageVisitsSerializer(Serializer): day = DateField() content_visits = IntegerField() communication_visits = IntegerField() assessment_visits = IntegerField() single_events = ListField() submission_events = ListField()
class ApplicantWithApplicationSerializer(ModelSerializer): full_name = CharField(read_only=True) birth_date = DateField( source="birth_info.date", read_only=True, ) program_code = CharField( source="university_info.program.code", read_only=True, ) faculty = CharField( source="university_info.program.faculty", read_only=True, ) application_process = ApplicationProcessSerializer(read_only=True) class Meta: model = Student fields = [ "id", "full_name", "birth_date", "program_code", "faculty", "application_process", ]
def test_validate_required_missing(): """ When given a None value the ListOrItemField validate method should raise a ValidationError. """ field = ListOrItemField(child=DateField(format=ISO_8601)) with pytest.raises(ValidationError): field.to_internal_value(None)
class WeeklyMetricsSerializer(Serializer): day = DateField() unique_visits = IntegerField() students = IntegerField() sessions = IntegerField() avg_session_duration = IntegerField() avg_session_pageviews = IntegerField()
class FileSerializer(ModelSerializer): name = CharField(max_length=300) photo = ImageField(required=False) is_public = BooleanField(required=False) delete_date = DateField(required=False) # read_only pk = IntegerField(read_only=True) issue_date = DateTimeField(read_only=True) update_date = DateTimeField(read_only=True) file_user = DictField(read_only=True, source="user_as_dict") file_parents = ListField(read_only=True, source="parents_as_list") file_children = ListField(read_only=True, source="children_as_list") # A `HiddenField` does not take input from the user, or present any output fk_user = HiddenField(default=CurrentUserDefault()) class Meta: model = FileModel fields = ( "pk", "fk_parent", "name", "photo", "is_public", "issue_date", "update_date", "delete_date", "file_user", "file_parents", "file_children", "fk_user", )
class FingerprintSerializer(NotEmptySerializer): """Serializer for the Fingerprint model.""" os_name = CharField(required=True, max_length=64) os_release = CharField(required=True, max_length=128) os_version = CharField(required=True, max_length=64) connection_host = CharField(required=False, max_length=256) connection_port = IntegerField(required=False, min_value=0) connection_uuid = UUIDField(required=True) cpu_count = IntegerField(required=False, min_value=0) cpu_core_per_socket = IntegerField(required=False, min_value=0) cpu_siblings = IntegerField(required=False, min_value=0) cpu_hyperthreading = NullBooleanField(required=False) cpu_socket_count = IntegerField(required=False, min_value=0) cpu_core_count = IntegerField(required=False, min_value=0) system_creation_date = DateField(required=False) infrastructure_type = ChoiceField( required=True, choices=SystemFingerprint.INFRASTRUCTURE_TYPE) virtualized_is_guest = NullBooleanField(required=True) virtualized_type = CharField(required=False, max_length=64) virtualized_num_guests = IntegerField(required=False, min_value=0) virtualized_num_running_guests = IntegerField(required=False, min_value=0) class Meta: """Meta class for FingerprintSerializer.""" model = SystemFingerprint fields = '__all__'
class PatientSerializer(Serializer): user = UserSerializer() date_of_birth = DateField() gender = CharField(max_length=1) mobileNumber = CharField(max_length=12) id = IntegerField(required=False) def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data) return Patient.objects.create(user=user, **validated_data) def update(self, instance, validated_data): user_data = validated_data.pop('user') user = User.objects.all().filter( username=user_data.get("username")).first() user.first_name = user_data['first_name'] user.last_name = user_data.get('last_name') user.email = user_data.get('email') user.save() instance = instance.first() instance.user = user instance.date_of_birth = validated_data.get("date_of_birth") instance.gender = validated_data.get("gender") instance.mobileNumber = validated_data.get("mobileNumber") instance.save() return instance
class RentalPropertySerializer(Serializer): # Details name = CharField() address = CharField() # Not always available latitude = DecimalField(max_digits=10, decimal_places=8) longitude = DecimalField(max_digits=11, decimal_places=8) offered_by = CharField(allow_null=True) description = ListField() # Dates date_available = DateField() post_date = DateTimeField() # Only applicable for certain websites # Costs rent_price = DecimalField(max_digits=20, decimal_places=2) application_fee = DecimalField(max_digits=10, decimal_places=2, allow_null=True) security_deposit = DecimalField(max_digits=10, decimal_places=2, allow_null=True) # Features size = DecimalField(max_digits=12, decimal_places=2, allow_null=True) bedrooms = IntegerField() bathrooms = IntegerField() amenities = ListField( allow_null=True ) # Interrelated with description; text parsing methods? tags = ListField() # URL Data listing_url = CharField()
def test_validate_non_dict(): """ When a DictField is given a non-dict value, then validate should raise a ValidationError. """ field = DictField(child=DateField()) with pytest.raises(ValidationError): field.to_internal_value('notADict')
def test_to_internal_value_list(): """ When given a valid list, the ListOrItemField to_internal_value method should utilize the list from-native logic. """ field = ListOrItemField(child=DateField(format=ISO_8601)) data = field.to_internal_value([date.today().isoformat()]) assert [date.today()] == data
def test_missing_required_list(): """ When a ListField requires a value, then validate should raise a ValidationError on a missing (None) value. """ field = ListField(child=DateField()) with pytest.raises(ValidationError): field.to_internal_value(None)
class LessonJournalQuerySerializer(Serializer): milgroup = IntegerField( required=True, validators=[PresentInDatabaseValidator(Milgroup, 'milgroup')]) date_from = DateField(required=False) date_to = DateField(required=False) def validate(self, attrs): if attrs['date_from'] > attrs['date_to']: raise ValueError('date_from should be greater or equal to date_to') return attrs def create(self, validated_data): pass def update(self, instance, validated_data): pass
def test_to_internal_value_item(): """ When given a valid item, the ListOrItemField to_internal_value method should utilize the item from-native logic. """ field = ListOrItemField(child=DateField(format=ISO_8601)) data = field.to_internal_value(date.today().isoformat()) assert date.today() == data
class UserSerializer(ModelSerializer): """DRF serializer for Users.""" created = DateField(source='date_joined', read_only=True) class Meta: model = User fields = ('id', 'username', 'created')
def test_to_representation_list(): """ When given a valid list, the ListOrItemField to_representation method should utilize the list to-native logic. """ field = ListOrItemField(child=DateField(format=ISO_8601)) data = field.to_representation([date.today()]) assert [date.today().isoformat()] == data
class GoalSerializer(ModelSerializer): dateGoal = DateField(format="%Y/%m/%d", input_formats=['%Y/%m/%d']) class Meta: model = Goal fields = [ 'id', 'goal', 'dateGoal', 'description', 'objective_id', 'done' ]
def test_to_representation_item(): """ When given a valid item, the ListOrItemField to_representation method should utilize the item to-native logic. """ field = ListOrItemField(child=DateField(format=ISO_8601)) data = field.to_representation(date.today()) assert date.today().isoformat() == data