class BuildJobSerializer(serializers.ModelSerializer): uuid = fields.UUIDField(format='hex', read_only=True) user = fields.SerializerMethodField() project = fields.SerializerMethodField() project_name = fields.SerializerMethodField() started_at = fields.DateTimeField(read_only=True) finished_at = fields.DateTimeField(read_only=True) class Meta: model = BuildJob fields = ( 'uuid', 'unique_name', 'user', 'sequence', 'description', 'created_at', 'updated_at', 'last_status', 'started_at', 'finished_at', 'is_running', 'is_done', 'project', 'project_name', ) def get_user(self, obj): return obj.user.username def get_project(self, obj): return obj.project.uuid.hex def get_project_name(self, obj): return obj.project.unique_name
class ActivitySerializer(serializers.ModelSerializer): title = fields.CharField(source="name") start = fields.DateTimeField(read_only=True) end = fields.DateTimeField(read_only=True) url = fields.URLField(source="get_absolute_url", read_only=True) textColor = fields.SerializerMethodField("get_text_color") class Meta: model = Activity fields = ( "title", "type", "start", "end", "location", "description", "url", "fb_event_id", "textColor", ) def get_text_color(self, obj): if obj.start_date == date.today(): return "#FFFFFF" return ""
class DataResourceSerializer(serializers.ModelSerializer): metadata = ResourceMetadataSerializer(many=True, required=False, read_only=True) #driver_config = hstore_fields.HStoreField(required=False) #metadata_properties = hstore_fields.HStoreField(required=False) last_change = fields.DateTimeField(required=False, read_only=True) last_refresh = fields.DateTimeField(required=False, read_only=True) next_refresh = fields.DateTimeField(required=False, read_only=True) bounding_box = gis_fields.GeometryField(required=False, read_only=True) import_log = fields.CharField(required=False, read_only=True) url = serializers.HyperlinkedIdentityField(view_name='data-resource-detail', lookup_field='slug') associated_pages = PageShortSerializer(many=True) class Meta: model = models.DataResource fields = ( 'url', 'title', 'slug', 'metadata', 'original_file', 'resource_url', 'metadata_url', 'metadata_xml', #'driver_config', #'metadata_properties', 'last_change', 'last_refresh', 'next_refresh', 'refresh_every', 'md5sum', 'bounding_box', 'import_log', 'id', 'associated_pages', )
class ExperimentJobSerializer(serializers.ModelSerializer): uuid = fields.UUIDField(format='hex', read_only=True) experiment = fields.SerializerMethodField() experiment_name = fields.SerializerMethodField() resources = JobResourcesSerializer(required=False) started_at = fields.DateTimeField(read_only=True) finished_at = fields.DateTimeField(read_only=True) class Meta: model = ExperimentJob fields = ( 'uuid', 'unique_name', 'sequence', 'role', 'experiment', 'experiment_name', 'last_status', 'is_running', 'is_done', 'created_at', 'updated_at', 'started_at', 'finished_at', 'resources', ) def get_experiment(self, obj): return obj.experiment.uuid.hex def get_experiment_name(self, obj): return obj.experiment.unique_name
def sync(self, request): now = timezone.now() response = { "time": None, # will be inserted after models updating "tags": [], "notes": [], } if "last_sync" in request.data: raw_last_sync = request.data["last_sync"] last_sync = fields.DateTimeField().to_internal_value(raw_last_sync) else: last_sync = datetime.min raw_tags = request.data.get("tags", []) self._apply_tags_changes(request, raw_tags) raw_notes = request.data.get("notes", []) self._apply_notes_changes(request, raw_notes) response["time"] = fields.DateTimeField().to_representation(now) response["tags"] += self._get_tags_changes(last_sync) response["notes"] += self._get_notes_changes(last_sync) return Response(response)
class BuildJobSerializer(serializers.ModelSerializer, ProjectMixin, UserMixin): uuid = fields.UUIDField(format='hex', read_only=True) user = fields.SerializerMethodField() project = fields.SerializerMethodField() started_at = fields.DateTimeField(read_only=True) finished_at = fields.DateTimeField(read_only=True) class Meta: model = BuildJob fields = ( 'id', 'uuid', 'name', 'unique_name', 'pod_id', 'user', 'description', 'created_at', 'updated_at', 'started_at', 'finished_at', 'last_status', 'tags', 'project', 'backend', 'is_managed', ) extra_kwargs = {'is_managed': {'read_only': True}}
class ExperimentSerializer(serializers.ModelSerializer): uuid = fields.UUIDField(format='hex', read_only=True) user = fields.SerializerMethodField() experiment_group = fields.SerializerMethodField() experiment_group_name = fields.SerializerMethodField() project = fields.SerializerMethodField() project_name = fields.SerializerMethodField() num_jobs = fields.SerializerMethodField() last_metric = fields.SerializerMethodField() started_at = fields.DateTimeField(read_only=True) finished_at = fields.DateTimeField(read_only=True) class Meta: model = Experiment fields = ( 'id', 'uuid', 'name', 'unique_name', 'user', 'description', 'created_at', 'updated_at', 'last_status', 'last_metric', 'started_at', 'finished_at', 'is_running', 'is_done', 'is_clone', 'project', 'project_name', 'experiment_group', 'tags', 'has_tensorboard', 'experiment_group_name', 'num_jobs', ) def get_user(self, obj): return obj.user.username def get_experiment_group(self, obj): return obj.experiment_group.uuid.hex if obj.experiment_group else None def get_experiment_group_name(self, obj): return obj.experiment_group.unique_name if obj.experiment_group else None def get_project(self, obj): return obj.project.uuid.hex def get_project_name(self, obj): return obj.project.unique_name def get_num_jobs(self, obj): return obj.jobs.count() def get_last_metric(self, obj): return {k: round(v, 7) for k, v in obj.last_metric.items()} if obj.last_metric else None
class PageSerializer(serializers.ModelSerializer): class Meta: model = Page fields = [ 'id', 'title', 'content', 'created_at', 'updated_at' ] id = fields.IntegerField(read_only=True) created_at = fields.DateTimeField(read_only=True) updated_at = fields.DateTimeField(read_only=True)
class ExperimentJobSerializer(serializers.ModelSerializer): uuid = fields.UUIDField(format='hex', read_only=True) resources = JobResourcesSerializer(required=False) started_at = fields.DateTimeField(read_only=True) finished_at = fields.DateTimeField(read_only=True) class Meta: model = ExperimentJob extra_kwargs = {'experiment': {'read_only': True}} fields = ('id', 'uuid', 'unique_name', 'role', 'experiment', 'last_status', 'created_at', 'updated_at', 'started_at', 'finished_at', 'resources', 'node_scheduled', 'pod_id')
class ExperimentSerializer(serializers.ModelSerializer, BuildMixin, ProjectMixin, UserMixin): uuid = fields.UUIDField(format='hex', read_only=True) original = fields.SerializerMethodField() user = fields.SerializerMethodField() experiment_group = fields.SerializerMethodField() project = fields.SerializerMethodField() build_job = fields.SerializerMethodField() started_at = fields.DateTimeField(read_only=True) finished_at = fields.DateTimeField(read_only=True) class Meta: model = Experiment fields = ( 'id', 'uuid', 'name', 'unique_name', 'user', 'description', 'created_at', 'updated_at', 'started_at', 'finished_at', 'last_status', 'original', 'cloning_strategy', 'project', 'experiment_group', 'build_job', 'backend', 'is_managed', 'framework', 'tags', 'last_metric', 'params', ) extra_kwargs = { 'original_experiment': { 'write_only': True }, 'is_managed': { 'read_only': True } } def get_original(self, obj): return obj.original_experiment.unique_name if obj.original_experiment else None def get_experiment_group(self, obj): return obj.experiment_group.unique_name if obj.experiment_group else None
class TagWikiSerializer(serializers.ModelSerializer): """The tag wiki serializer """ excerpt_last_edit_date = fields.DateTimeField( source='excerpt.last_edit_date', default=None) body_last_edit_date = fields.DateTimeField(source='wiki.last_edit_date', default=None) excerpt = fields.CharField(source='excerpt.body', default=None) tag_name = fields.CharField(source='name') class Meta: model = models.Tag fields = ('excerpt_last_edit_date', 'body_last_edit_date', 'excerpt', 'tag_name')
class ExperimentSerializer(serializers.ModelSerializer): uuid = fields.UUIDField(format='hex', read_only=True) original = fields.SerializerMethodField() user = fields.SerializerMethodField() experiment_group = fields.SerializerMethodField() build_job = fields.SerializerMethodField() project = fields.SerializerMethodField() started_at = fields.DateTimeField(read_only=True) finished_at = fields.DateTimeField(read_only=True) class Meta: model = Experiment fields = ( 'id', 'uuid', 'name', 'unique_name', 'user', 'description', 'created_at', 'updated_at', 'started_at', 'finished_at', 'last_status', 'original', 'cloning_strategy', 'project', 'experiment_group', 'build_job', 'backend', 'framework', 'tags', 'last_metric', 'declarations', ) def get_user(self, obj): return obj.user.username def get_original(self, obj): return obj.original_experiment.unique_name if obj.original_experiment else None def get_experiment_group(self, obj): return obj.experiment_group.unique_name if obj.experiment_group else None def get_project(self, obj): return obj.project.unique_name def get_build_job(self, obj): return obj.build_job.unique_name if obj.build_job else None
class HistorySerializerMixIn(Serializer): history_id = fields.IntegerField() history_date = fields.DateTimeField() history_change_reason = fields.CharField() history_type = fields.CharField() history_user_id = fields.IntegerField() history_user = UserSerializer() class Meta: fields = ('history_id', 'history_date', 'history_change_reason', 'history_type', 'history_type', 'history_user_id', 'history_user') def to_representation(self, instance): ret = OrderedDict() fields = self._readable_fields # noqa for field in fields: simplify_nested_serializer(field) try: attribute = field.get_attribute(instance) if attribute is not None: ret[field.field_name] = field.to_representation(attribute) else: ret[field.field_name] = None except AttributeError: ret[field.field_name] = None return ret
class HomeworkSerializer(serializers.ModelSerializer): deadline = fields.DateTimeField(input_formats=['%d-%m-%Y %H:%M']) class Meta: model = HomeworkModel fields = ['id', 'description', 'deadlineDate', 'deadlineTime', 'isOverdue', 'Class', "deadline"]
class PersonsListSerializer(Serializer): name = fields.CharField(required=True) last_name = fields.CharField(required=True) phone_number = fields.CharField(required=True) timestamp = fields.DateTimeField(required=True) address = fields.CharField(required=True) review = fields.SerializerMethodField() def get_review(self, obj): inst = obj.reviews.order_by('timestamp').last() if inst is not None: review = { 'text': inst.text, 'author': '{} {}'.format(inst.author.name, inst.author.last_name), 'rating': inst.rating, 'timestamp': inst.timestamp.isoformat(), 'rewies_count': obj.reviews.count(), } else: review = { 'text': 'There are no reviews yet', 'rewies_count': 0, } return review
class FactsSerializer(Serializer): """Serializer for HBI facts.""" source_types = fields.ListField() last_discovered = fields.DateTimeField() qpc_server_version = fields.CharField(default=server_version) qpc_server_id = fields.CharField(default=get_server_id)
class StockTransferOutSerializer(ModelSerializer): id = fields.CharField(required=False) detail = StockTransferOutDetailSerializer(source='list_detail', many=True, read_only=True) created_at = fields.DateTimeField(read_only=True) created_by_detail = UserSerializer(read_only=True, source='created_by') created_by__id = fields.CharField(read_only=True) total = fields.IntegerField(read_only=True) promotion__id = fields.IntegerField(required=False, read_only=True) promotion_detail = PromotionSerializer(read_only=True, source='promotion') customer_detail = CustomerSerializer(read_only=True, source='customer') customer__id = fields.CharField(read_only=True) def validate_promotion_code(self, promotion_code): if promotion_code is None or promotion_code == "": return None promotions = Promotion.objects.filter(code=promotion_code) if promotions.count() == 0: raise ValidationError('promotion does not exist') if promotions[0].is_used: raise ValidationError('promotion is used') return promotion_code class Meta: model = StockTransferOut fields = '__all__'
def test_notifications(self): experiment = self.experiments['test-1'] steps = [ ExperimentNotification.objects.create( experiment=experiment, title='title %s' % idx, text='text %s' % idx, notify_after=datetime.datetime.utcnow()) for idx in range(1, 4) ] url = reverse('experiment-detail', args=(experiment.pk, )) resp = self.client.get(url) data = json.loads(str(resp.content, encoding='utf8')) date_field = fields.DateTimeField() self.assertEqual(len(steps), len(data['notifications'])) for idx in range(0, len(steps)): step = steps[idx] result = data['notifications'][idx] self.assertEqual(step.title, result['title']) self.assertEqual(step.text, result['text']) self.assertEqual( '%sZ' % date_field.to_representation(step.notify_after), result['notify_after'])
def test_create_account(self): user = self.create_user_and_login() url = reverse("account-list") data = {"name": "Foo"} response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertTrue(Account.objects.count(), 1) self.assertTrue(AccountMember.objects.count(), 1) account = Account.objects.first() account_member = AccountMember.objects.first() self.assertEqual( response.data, { "id": str(account.id), "name": account.name, "created_at": fields.DateTimeField().to_representation(account.created_at), }, ) self.assertEqual(account.name, "Foo") self.assertEqual(account_member.account_id, account.id) self.assertEqual(account_member.user_id, user.id)
def test_create_webhook(self): user, account = self.create_account_and_login() url = reverse("webhook-list") data = {"name": "Foo"} response = self.client.post( url, data, **{"HTTP_X_WH_ACCOUNT_ID": str(account.id)}) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertTrue(Webhook.objects.count(), 1) webhook = Webhook.objects.first() self.assertEqual( response.data, { "id": str(webhook.id), "name": webhook.name, "created_at": fields.DateTimeField().to_representation(webhook.created_at), }, )
class ActivitySerializer(serializers.ModelSerializer): title = fields.CharField(source='name') start = fields.DateTimeField(read_only=True) end = fields.DateTimeField(read_only=True) url = fields.URLField(source='get_absolute_url', read_only=True) textColor = fields.SerializerMethodField('get_text_color') class Meta: model = Activity fields = ('title', 'type', 'start', 'end', 'location', 'description', 'url', 'fb_event_id', 'textColor') def get_text_color(self, obj): if obj.start_date == date.today(): return '#FFFFFF' return ''
class MessageDataSerializer(serializers.ModelSerializer): date = fields.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S.%f']) class Meta: model = MessageData fields = [ "message_id", "author_id", "content", "date" ] def create(self, data): user_id = data["author_id"] user = UserData.objects.get_or_create(user_id=user_id)[0] user.nb_msg += 1 user.save() message = MessageData.objects.get_or_create( message_id=data["message_id"] )[0] message.author_id = data.get("author_id", message.author_id) message.content = data.get("content", message.content) message.date = data.get("date", message.date) message.save() return message
class TasksSerializer(serializers.ModelSerializer): date_of_creation = fields.DateTimeField( input_formats=['%Y-%m-%dT%H:%M:%S.%fZ']) class Meta: model = Task fields = ("id", "task_name", "description", "tags", "date_of_creation")
class ItemSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() label = serializers.SerializerMethodField() profile = ProfileSerializer() user = serializers.StringRelatedField() publish = fields.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S:%fZ'], format='%A,%dth %B,%Y %I:%M:%S%p') class Meta: model = Item fields = ( 'id', 'title', 'price', 'discount_price', 'category', 'label', 'slug', 'description', 'image', 'publish', 'profile', 'user', ) def get_category(self, obj): return obj.get_category_display() def get_label(self, obj): return obj.get_label_display()
def test_basic_mapping(self, assert_dict_equals): """ Confirm that the serializer can still handle models w/ standard Django fields """ class TestSerializer(DjongoModelSerializer): class Meta: model = GenericModel fields = '__all__' expected_dict = { 'id': drf_fields.IntegerField(label='ID', read_only=True), 'big_int': drf_fields.IntegerField(max_value=9223372036854775807, min_value=-9223372036854775808), 'bool': drf_fields.BooleanField(), 'char': drf_fields.CharField(max_length=20), 'comma_int': ("CharField(validators=[<django.core.validators.RegexValidator " "object>, <django.core.validators.MaxLengthValidator object>])"), 'date': drf_fields.DateField(), 'date_time': drf_fields.DateTimeField(), 'decimal': drf_fields.DecimalField(decimal_places=5, max_digits=10), 'email': drf_fields.EmailField(max_length=254), 'float': drf_fields.FloatField(), 'integer': drf_fields.IntegerField(max_value=2147483647, min_value=-2147483648), 'null_bool': drf_fields.NullBooleanField(required=False), 'pos_int': drf_fields.IntegerField(max_value=2147483647, min_value=0), 'pos_small_int': drf_fields.IntegerField(max_value=32767, min_value=0), 'slug': drf_fields.SlugField(allow_unicode=False, max_length=50), 'small_int': drf_fields.IntegerField(max_value=32767, min_value=-32768), 'text': "CharField(style={'base_template': 'textarea.html'})", 'time': drf_fields.TimeField(), 'url': drf_fields.URLField(max_length=200), 'ip': drf_fields.IPAddressField(), 'uuid': "ModelField(model_field=<django.db.models.fields.UUIDField: uuid>)", } assert_dict_equals(TestSerializer().get_fields(), expected_dict)
def inner(value): if isinstance(value, datetime.datetime): f = rest_fields.DateTimeField() return f.to_representation(value) if isinstance(value, datetime.date): f = rest_fields.DateField() return f.to_representation(value) raise ValueError("Invalid value: {}".format(value))
class TipSerializer(serializers.ModelSerializer): tweeted_at = fields.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%SZ']) python_tip = fields.CharField(max_length=140) class Meta: model = Tip fields = ("id", "tweeted_at", "python_tip", "link", "likes", "retweets", "who_posted", "published") read_only_fields = "id",
class BookmarkSerializer(serializers.HyperlinkedModelSerializer): sourceId = fields.CharField(source='source_id') createdAt = fields.DateTimeField(source='created_at', read_only=True) source = SourceBaseSerializer(read_only=True) class Meta: model = Bookmark fields = ('id', 'sourceId', 'createdAt', 'source')
class RunSerializer(serializers.ModelSerializer, CloningMixin, PipelineMixin, SettingsMixin): uuid = fields.UUIDField(format="hex", read_only=True) original = fields.SerializerMethodField() pipeline = fields.SerializerMethodField() started_at = fields.DateTimeField(read_only=True) finished_at = fields.DateTimeField(read_only=True) settings = fields.SerializerMethodField() meta_kind = fields.SerializerMethodField() class Meta: model = get_run_model() fields = ( "uuid", "name", "description", "created_at", "updated_at", "started_at", "finished_at", "duration", "kind", "meta_kind", "meta_info", "status", "pipeline", "original", "is_managed", "inputs", "outputs", "tags", "deleted", "settings", ) extra_kwargs = { "is_managed": { "read_only": True }, "cloning_kind": { "read_only": True }, } def get_meta_kind(self, obj): meta_info = obj.meta_info or {} return meta_info.get("meta_kind")
class IdentifierSerializer(serializers.ModelSerializer): birth = fields.DateTimeField(format='%d/%m/%Y', required=True) dateofissue = fields.DateTimeField(format='%d/%m/%Y', required=True) images = ImageSerializer(many=True, read_only=True) surname = fields.CharField(required=True) name = fields.CharField(required=True) patronymic = fields.CharField(required=True) passport = fields.IntegerField(required=True) districtcode = fields.IntegerField(required=True) districtname = fields.CharField(required=True) address = fields.CharField(required=True) class Meta: model = models.Identifier fields = ('id', 'surname', 'name', 'patronymic', 'passport', 'birth', 'placeofbirth', 'dateofissue', 'districtcode', 'districtname', 'address', 'images') def create(self, validated_data): images_data = self.context.get('view').request.FILES owner_id = self.context['request'].user.id if len(list(images_data.values())) > 2: raise serializers.ValidationError({ 'images': 'you can add 8 files', }) gallery_identifier = models.Identifier.objects.create( surname=validated_data.get('surname'), name=validated_data.get('name'), patronymic=validated_data.get('patronymic'), passport=validated_data.get('passport'), birth=validated_data.get('birth'), owner_id=owner_id, placeofbirth=validated_data.get('placeofbirth'), dateofissue=validated_data.get('dateofissue'), districtcode=validated_data.get('districtcode'), districtname=validated_data.get('districtname'), address=validated_data.get('address')) gallery_identifier.save() for image_data in images_data.values(): models.PassportImage.objects.create( gallery_capsule=gallery_identifier, passport_file=image_data) return gallery_identifier