Python rest_framework.serializers.DateTimeField() Examples

The following are 5 code examples for showing how to use rest_framework.serializers.DateTimeField(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.serializers , or try the search function .

Example 1
Project: cmdb   Author: open-cmdb   File: initialize.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def add_serializer(table):
    fields = table.fields.all()
    attributes = {}
    for field in fields:
        args = {
            "label": field.alias
        }
        if not field.required:
            args["default"] = None
            args["allow_null"] = True
        if field.type == 3:
            args["format"] = "%Y-%m-%dT%H:%M:%S"
        elif field.type == 6:
            args["protocol"] = "IPv4"
        f = FIELD_TYPE_MAP[field.type](**args)
        if(field.is_multi):
            attributes[field.name] = serializers.ListField(default=[], child=f)
        else:
            attributes[field.name] = f
        # if(field.type == 0):
        #     attributes["validate_{}".format(field.name)] = empty_none
    #创建者拿到视图aQ!
    # attributes["S-creator"] = serializers.CharField(read_only=True, default=serializers.CurrentUserDefault())
    attributes["S-creation-time"] = serializers.DateTimeField(read_only=True, format="%Y-%m-%dT%H:%M:%S",
                                                              default=datetime.datetime.now)
    attributes["S-last-modified"] = serializers.CharField(default=None, allow_null=True, read_only=True, label="最后修改人")
    serializer = type(table.name, (Serializer, ), attributes)
    setattr(app_serializers, table.name, serializer) 
Example 2
Project: cmdb   Author: open-cmdb   File: views.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def update(self, request, *args, **kwargs):
        try:
            res = es.get(index="test_12", doc_type="one", id=kwargs["pk"])
        except NotFoundError as exc:
            raise exceptions.NotFound("Document {} was not found in Type one of Index test_12".format(kwargs["pk"]))
        except Exception as exc:
            raise exceptions.APIException("内部错误, 错误类型:{}".format(type(exc)))
        his_data = res["_source"]
        partial = kwargs.get("partial", False)
        serializer = self.get_serializer(data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)

        data = copy.copy(his_data)
        is_equal = True
        for k,v in serializer.validated_data.items():
            if k[0] == "S":
                continue
            if isinstance(serializer.fields.fields[k], serializers.DateTimeField):
                if isinstance(v, list):
                    v = list(map(lambda x: x.isoformat(), v))
                else:
                    v = v.isoformat()
            data[k] = v
            if his_data[k] != v:
                is_equal = False
                break
        if is_equal:
            raise exceptions.ParseError(detail="No field changes")
        his_data.pop("S_creator")
        his_data.pop("S_creation_time")
        his_data["S_data_id"] = kwargs["pk"]
        his_data["S_changer"] = request.user.username
        his_data["S_update_time"] = datetime.datetime.now()
        try:
            es.index(index="test_22", doc_type="one", id=uuid.uuid1(), body=his_data)
            res = es.index(index="test_12", doc_type="one", id=kwargs["pk"], body=data)
        except Exception as exc:
            raise exceptions.APIException("内部错误,错误类型: {}".format(type(exc)))
        return Response(res) 
Example 3
Project: graphene-django   Author: graphql-python   File: test_field_converter.py    License: MIT License 5 votes vote down vote up
def test_should_date_time_convert_datetime():
    assert_conversion(serializers.DateTimeField, graphene.types.datetime.DateTime) 
Example 4
Project: pydantic   Author: samuelcolvin   File: test_drf.py    License: MIT License 5 votes vote down vote up
def __init__(self, allow_extra):
        class Model(serializers.Serializer):
            id = serializers.IntegerField()
            client_name = serializers.CharField(max_length=255, trim_whitespace=False)
            sort_index = serializers.FloatField()
            # client_email = serializers.EmailField(required=False, allow_null=True)
            client_phone = serializers.CharField(max_length=255, trim_whitespace=False, required=False, allow_null=True)

            class Location(serializers.Serializer):
                latitude = serializers.FloatField(required=False, allow_null=True)
                longitude = serializers.FloatField(required=False, allow_null=True)
            location = Location(required=False, allow_null=True)

            contractor = serializers.IntegerField(required=False, allow_null=True, min_value=0)
            upstream_http_referrer = serializers.CharField(
                max_length=1023, trim_whitespace=False, required=False, allow_null=True
            )
            grecaptcha_response = serializers.CharField(min_length=20, max_length=1000, trim_whitespace=False)
            last_updated = serializers.DateTimeField(required=False, allow_null=True)

            class Skill(serializers.Serializer):
                subject = serializers.CharField()
                subject_id = serializers.IntegerField()
                category = serializers.CharField()
                qual_level = serializers.CharField()
                qual_level_id = serializers.IntegerField()
                qual_level_ranking = serializers.FloatField(default=0)
            skills = serializers.ListField(child=Skill())

        self.allow_extra = allow_extra  # unused
        self.serializer = Model 
Example 5
Project: drf-haystack   Author: rhblind   File: serializers.py    License: MIT License 5 votes vote down vote up
def get_text(self, instance):
        """
        Haystack facets are returned as a two-tuple (value, count).
        The text field should contain the faceted value.
        """
        instance = instance[0]
        if isinstance(instance, (six.text_type, six.string_types)):
            return serializers.CharField(read_only=True).to_representation(instance)
        elif isinstance(instance, datetime):
            return serializers.DateTimeField(read_only=True).to_representation(instance)
        return instance