• drf 和django 字段参数解析


    drf:

    https://www.django-rest-framework.org/api-guide/fields/#string-fields

    核心字段:

    每个序列化器字段类构造函数都至少接受这些参数。某些Field类采用其他特定于字段的参数,但应始终接受以下内容:

    read_only

    只读字段包含在API输出中,但在创建或更新操作期间不应包含在输入中。错误地包含在序列化器输入中的所有“ read_only”字段都将被忽略。

    进行设置True以确保序列化表示形式时使用该字段,而在反序列化期间创建或更新实例时不使用该字段。

    默认为 False

    write_only

    进行设置True以确保在更新或创建实例时可以使用该字段,但是在序列化表示形式时不包括该字段。

    默认为 False

    required

    如果反序列化过程中未提供字段,通常会引发错误。如果反序列化过程中不需要此字段,则设置为false。

    将此设置为,False还可以在序列化实例时从输出中省略对象属性或字典键。如果不存在该密钥,则它将不会直接包含在输出表示中。

    默认为True

    default

    如果设置,则给出默认值,如果没有提供输入值,该默认值将用于该字段。如果未设置,则默认行为是根本不填充该属性。

    default过程中部分更新操作不适用。在部分更新的情况下,仅传入数据中提供的字段将返回经过验证的值。

    可以设置为函数或其他可调用函数,在这种情况下,每次使用该值时都会对其求值。调用时,它将不接收任何参数。如果可调用对象具有requires_context = True属性,则序列化器字段将作为参数传递。

    例如:

    参数:error_messages:

    class CharField(Field):
    default_error_messages = {
    'invalid': _('Not a valid string.'),
    'blank': _('This field may not be blank.'),
    'max_length': _('Ensure this field has no more than {max_length} characters.'),
    'min_length': _('Ensure this field has at least {min_length} characters.'),
    }

    class IntegerField(Field):
    default_error_messages = {
    'invalid': _('A valid integer is required.'),
    'max_value': _('Ensure this value is less than or equal to {max_value}.'),
    'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
    'max_string_length': _('String value too large.')
    }

    class DecimalField(Field):
    default_error_messages = {
    'invalid': _('A valid number is required.'),
    'max_value': _('Ensure this value is less than or equal to {max_value}.'),
    'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
    'max_digits': _('Ensure that there are no more than {max_digits} digits in total.'),
    'max_decimal_places': _('Ensure that there are no more than {max_decimal_places} decimal places.'),
    'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.'),
    'max_string_length': _('String value too large.')
    }

    class DateTimeField(Field):
    default_error_messages = {
    'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}.'),
    'date': _('Expected a datetime but got a date.'),
    'make_aware': _('Invalid datetime for the timezone "{timezone}".'),
    'overflow': _('Datetime value out of range.')
    }

    class PrimaryKeyRelatedField(RelatedField):
    default_error_messages = {
    'required': _('This field is required.'),
    'does_not_exist': _('Invalid pk "{pk_value}" - object does not exist.'),
    'incorrect_type': _('Incorrect type. Expected pk value, received {data_type}.'),
    }
    class StringRelatedField(RelatedField):
    """
    A read only field that represents its targets using their
    plain string representation.
    """

    def __init__(self, **kwargs):
    kwargs['read_only'] = True
    super().__init__(**kwargs)

    def to_representation(self, value):
    return str(value)
    class ChoiceField(Field):
    default_error_messages = {
    'invalid_choice': _('"{input}" is not a valid choice.')
    }
    
    
    class FloatField(Field):
    default_error_messages = {
    'invalid': _('A valid number is required.'),
    'max_value': _('Ensure this value is less than or equal to {max_value}.'),
    'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
    'max_string_length': _('String value too large.')
    }

    class SerializerMethodField(Field):
    """
    A read-only field that get its representation from calling a method on the
    parent serializer class. The method called will be of the form
    "get_{field_name}", and should take a single argument, which is the
    object being serialized.

    For example:

    class ExampleSerializer(self):
    extra_info = SerializerMethodField()

    def get_extra_info(self, obj):
    return ... # Calculate some data to return.
    """
    def __init__(self, method_name=None, **kwargs):
    self.method_name = method_name
    kwargs['source'] = '*'
    kwargs['read_only'] = True
    super().__init__(**kwargs)

    class EmailField(CharField):
    default_error_messages = {
    'invalid': _('Enter a valid email address.')
    }
    class FileField(Field):
    default_error_messages = {
    'required': _('No file was submitted.'),
    'invalid': _('The submitted data was not a file. Check the encoding type on the form.'),
    'no_name': _('No filename could be determined.'),
    'empty': _('The submitted file is empty.'),
    'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'),
    }
    class JSONField(Field):
    default_error_messages = {
    'invalid': _('Value must be valid JSON.')
    }


    其他参数:

    请注意,设置default值意味着该字段不是必需的。同时包含defaultrequired关键字参数都是无效的,并且会引发错误。

    allow_null

    如果None传递给序列化器字段,通常会引发错误将此关键字参数设置为TrueifNone应该被视为有效值。

    请注意,如果没有explicit default,将此参数设置为True会隐含序列化输出defaultnull,但并不隐含输入反序列化的默认值。

    默认为 False

    source

    将用于填充字段的属性的名称。可以是仅接受self参数的方法,例如URLField(source='get_absolute_url'),也可以使用点分符号遍历属性,例如EmailField(source='user.email')当使用点符号序列化字段时,default如果在属性遍历期间不存在任何对象或对象为空,则可能需要提供一个值。

    该值source='*'具有特殊含义,用于指示应将整个对象传递给该字段。这对于创建嵌套表示或对于需要访问完整对象才能确定输出表示的字段很有用。

    默认为字段名称。

    validators

    验证器功能列表,应将其应用于输入字段输入,并引发验证错误或简单地返回。验证器功能通常应该提高serializers.ValidationError,但是ValidationError还支持Django的内置函数以便与Django代码库或第三方Django包中定义的验证器兼容。

    error_messages

    错误代码到错误消息的字典。

    label

    一个简短的文本字符串,可用作HTML表单字段或其他描述性元素中的字段名称。

    help_text

    可用作在HTML表单字段或其他描述性元素中对该字段进行描述的文本字符串。

    initial

    该值应用于预先填充HTML表单字段的值。您可以将callable传递给它,就像处理任何常规Django一样Field

    import datetime
    from rest_framework import serializers
    class ExampleSerializer(serializers.Serializer):
        day = serializers.DateField(initial=datetime.date.today)
    

    style

    键值对字典,可用于控制渲染器应如何渲染字段。

    这里的两个例子是'input_type''base_template'

    # Use <input type="password"> for the input.
    password = serializers.CharField(
        style={'input_type': 'password'}
    )
    
    # Use a radio input instead of a select input.
    color_channel = serializers.ChoiceField(
        choices=['red', 'green', 'blue'],
        style={'base_template': 'radio.html'}
    )
    

    有关更多详细信息,请参见HTML&Forms文档。

     




    serializers.CharField

    文本表示形式。(可选)验证文本是否短于max_length和长于min_length

    对应于django.db.models.fields.CharFielddjango.db.models.fields.TextField

    签名: CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)

    • max_length -验证输入的字符数不超过此数量。
    • min_length -验证输入的字符数不少于此。
    • allow_blank-如果设置为True,则应将空字符串视为有效值。如果设置为,False则认为空字符串无效,并且将引发验证错误。默认为False
    • trim_whitespace-如果设置为,True则修剪前导和尾随空格。默认为True

    allow_null选项也可用于字符串字段,尽管不建议使用allow_blank设置allow_blank=True都是有效的allow_null=True,但是这样做意味着对于字符串表示而言,将存在两种不同类型的空值,这可能导致数据不一致和细微的应用程序错误。

    IntegerField

    An integer representation.

    Corresponds to django.db.models.fields.IntegerFielddjango.db.models.fields.SmallIntegerFielddjango.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField.

    SignatureIntegerField(max_value=None, min_value=None)

    • max_value Validate that the number provided is no greater than this value.
    • min_value Validate that the number provided is no less than this value.

    FloatField

    A floating point representation.

    Corresponds to django.db.models.fields.FloatField.

    Signature: FloatField(max_value=None, min_value=None)

    • max_value Validate that the number provided is no greater than this value.
    • min_value Validate that the number provided is no less than this value
    
    

    DecimalField

    A decimal representation, represented in Python by a Decimal instance.

    Corresponds to django.db.models.fields.DecimalField.

    SignatureDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)

    • max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places.
    • decimal_places The number of decimal places to store with the number.
    • coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting localize will force the value to True.
    • max_value Validate that the number provided is no greater than this value.
    • min_value Validate that the number provided is no less than this value.
    • localize Set to True to enable localization of input and output based on the current locale. This will also force coerce_to_string to True. Defaults to False. Note that data formatting is enabled if you have set USE_L10N=True in your settings file.
    • rounding Sets the rounding mode used when quantising to the configured precision. Valid values are decimal module rounding modes. Defaults to None.

    DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None)

    • format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation. In this case the datetime encoding will be determined by the renderer.
    • input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
    • default_timezone - A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone. If USE_TZ is disabled, then datetime objects will be naive.

    DateTimeField format strings.

    Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z')

    When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class.

    
    

    ChoiceField

    A field that can accept a value out of a limited set of choices.

    Used by ModelSerializer to automatically generate fields if the corresponding model field includes a choices=… argument.

    Signature: ChoiceField(choices)

    • choices - A list of valid values, or a list of (key, display_name) tuples.
    • allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
    • html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None.
    • html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…"

    Both the allow_blank and allow_null are valid options on ChoiceField, although it is highly recommended that you only use one and not both. allow_blank should be preferred for textual choices, and allow_null should be preferred for numeric or other non-textual choices.

    
    

    FileField

    A file representation. Performs Django's standard FileField validation.

    Corresponds to django.forms.fields.FileField.

    Signature: FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)

    • max_length - Designates the maximum length for the file name.
    • allow_empty_file - Designates if empty files are allowed.
    • use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.

    ListField

    A field class that validates a list of objects.

    SignatureListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)

    • child - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
    • allow_empty - Designates if empty lists are allowed.
    • min_length - Validates that the list contains no fewer than this number of elements.
    • max_length - Validates that the list contains no more than this number of elements.

    For example, to validate a list of integers you might use something like the following:

    scores = serializers.ListField(
       child=serializers.IntegerField(min_value=0, max_value=100)
    )

    The ListField class also supports a declarative style that allows you to write reusable list field classes.

    class StringListField(serializers.ListField):
        child = serializers.CharField()
    
    

     Custom Field

    Let's look at an example of serializing a class that represents an RGB color value:

    class Color:
        """
        A color represented in the RGB colorspace.
        """
        def __init__(self, red, green, blue):
            assert(red >= 0 and green >= 0 and blue >= 0)
            assert(red < 256 and green < 256 and blue < 256)
            self.red, self.green, self.blue = red, green, blue
    
    class ColorField(serializers.Field):
        """
        Color objects are serialized into 'rgb(#, #, #)' notation.
        """
        def to_representation(self, value):
            return "rgb(%d, %d, %d)" % (value.red, value.green, value.blue)
    
        def to_internal_value(self, data):
            data = data.strip('rgb(').rstrip(')')
            red, green, blue = [int(col) for col in data.split(',')]
            return Color(red, green, blue)


    最后关于自定义序列化读和写:

    .to_representation() - Override this to support serialization, for read operations.
    .to_internal_value() - Override this to support deserialization, for write operations.
    .create() and .update() - Override either or both of these to support saving instances.
    Because this class provides the same interface as the Serializer class, you can use it with the existing generic class-based views exactly as you would for a regular Serializer or ModelSerializer.

    Example   to_representation for  read_only 

    For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration:

    import time
    
    class TrackListingField(serializers.RelatedField):
        def to_representation(self, value):
            duration = time.strftime('%M:%S', time.gmtime(value.duration))
            return 'Track %d: %s (%s)' % (value.order, value.name, duration)
    
    class AlbumSerializer(serializers.ModelSerializer):
        tracks = TrackListingField(many=True)
    
        class Meta:
            model = Album
            fields = ['album_name', 'artist', 'tracks']

    This custom field would then serialize to the following representation:

    {
        'album_name': 'Sometimes I Wish We Were an Eagle',
        'artist': 'Bill Callahan',
        'tracks': [
            'Track 1: Jim Cain (04:39)',
            'Track 2: Eid Ma Clack Shaw (04:19)',
            'Track 3: The Wind and the Dove (04:34)',
            ...
        ]
    }



    关于扩充参数:
    1.exclude排除
    2.depth 外键深度控制最大10层
    3.获取指定字段自定义
    4.source
    5.read_only字段控制
    6.extra_kwargs
    7.get_xxx_display 取choice枚举值

    class AccountSerializer(serializers.ModelSerializer):
        class Meta:
            model = Account
            exclude = ['users']

    The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option:

    class AccountSerializer(serializers.ModelSerializer):
        class Meta:
            model = Account
            fields = ['id', 'account_name', 'users', 'created']
            depth = 1
     
    class SerializerBook(serializers.ModelSerializer):
    publish_name = serializers.SerializerMethodField()
    author_info = serializers.SerializerMethodField()

    class Meta:
    model = Book
    fields = ['id', 'name', 'price', 'author', 'publish', 'author_info', 'publish_name']

    extra_kwargs = {
    'author': {'write_only': True},
    'publish': {'write_only': True}
    }

    # 语法格式 get_Serializer序列化字段名
    def get_publish_name(self, book):
    publish_name = book.publish.publish_name
    return publish_name

    def get_author_info(self, book):
    """ 可自定义返回字段"""
    # # res=[{"name":author.name,"id":author.id,"sex":author.sex} for author in book.author.all()]
    serial = SerializerAuthor(instance=book.author.all(), many=True)
    return serial.data
     
    class AccountSerializer(serializers.ModelSerializer):
        class Meta:
            model = Account
            fields = ['id', 'account_name', 'users', 'created']
            read_only_fields = ['account_name']
    class SerializerAuthor(serializers.ModelSerializer):
    # todo 语法格式 get_字段_display
    sex_name = serializers.CharField(source='get_sex_display', read_only=True)
    name = serializers.CharField(validators=[])

    class Meta:
    model = Author
    fields = ['name', 'phone_number', 'sex', 'sex_name']
    extra_kwargs = {
    'sex': {'write_only': True}
    }
     

  • 相关阅读:
    Lake Counting
    部分和问题
    迷宫最短路
    sublime 的使用技巧
    数组
    Factorial Trailing Zeroes
    Top K Frequent Elements
    Number of Connected Component in An Undirected Graph
    Zigzag Iterator
    Single Number III
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/14554787.html
Copyright © 2020-2023  润新知