• Django模型(字段选项)


    1.null

    参数作用:True则在数据库中将空值储存为NULL,默认False
    null影响数据库的储存,blank影响表单的输入
    
    注意:
    1.基于字符串的字段类型中避免使用null,如果字符串字段中出现null=True,就意味着两种情况,第一种是空字符串.另一种是空值NULL(no data).Django习惯使用空字符串而不是空值null(无数据).
    一个例外是, 字符串字段拥有unique=True和blank=True(唯一且可以为空)时,null=True.就保证了不违反唯一性条件.
    示例:
    class CharField(max_length=None,unique=True,blank=True,null=True)
    #需要避免出现多个空值从而违反唯一条件约束.
    
    2.Oracle数据库默认将空值储存为null,此字段选项从而不作考虑.
    
    3.如果你想要在BooleanField允许null值,使用NullBooleanField替代即可.
    

      

    2.blank

    Field.blank:True则该字段允许为空,默认False.
    要注意blank和null的不同,null和数据库相关,blank和验证器相关
    如果字段blank=True,表单验证将允许输入一个空值,否则必须填值

    3.choices
    Field.choices

    An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field. If this is given, the default form widget will be a select box with these choices instead of the standard text field.

    The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name. For example:

    YEAR_IN_SCHOOL_CHOICES = (
    ('FR', 'Freshman'),
    ('SO', 'Sophomore'),
    ('JR', 'Junior'),
    ('SR', 'Senior'),
    )
    Generally, it’s best to define choices inside a model class, and to define a suitably-named constant for each value:

    from django.db import models

    class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = (
    (FRESHMAN, 'Freshman'),
    (SOPHOMORE, 'Sophomore'),
    (JUNIOR, 'Junior'),
    (SENIOR, 'Senior'),
    )
    year_in_school = models.CharField(
    max_length=2,
    choices=YEAR_IN_SCHOOL_CHOICES,
    default=FRESHMAN,
    )

    def is_upperclass(self):
    return self.year_in_school in (self.JUNIOR, self.SENIOR)
    Though you can define a choices list outside of a model class and then refer to it, defining the choices and names for each choice inside the model class keeps all of that information with the class that uses it, and makes the choices easy to reference (e.g, Student.SOPHOMORE will work anywhere that the Student model has been imported).

    You can also collect your available choices into named groups that can be used for organizational purposes:

    MEDIA_CHOICES = (
    ('Audio', (
    ('vinyl', 'Vinyl'),
    ('cd', 'CD'),
    )
    ),
    ('Video', (
    ('vhs', 'VHS Tape'),
    ('dvd', 'DVD'),
    )
    ),
    ('unknown', 'Unknown'),
    )
    The first element in each tuple is the name to apply to the group. The second element is an iterable of 2-tuples, with each 2-tuple containing a value and a human-readable name for an option. Grouped options may be combined with ungrouped options within a single list (such as the unknown option in this example).

    For each model field that has choices set, Django will add a method to retrieve the human-readable name for the field’s current value. See get_FOO_display() in the database API documentation.

    Note that choices can be any iterable object – not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you’re probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn’t change much, if ever.

    Unless blank=False is set on the field along with a default then a label containing "---------" will be rendered with the select box. To override this behavior, add a tuple to choices containing None; e.g. (None, 'Your String For Display'). Alternatively, you can use an empty string instead of None where this makes sense - such as on a CharField.

    4.db_column
    Field.db_column
    The name of the database column to use for this field. If this isn’t given, Django will use the field’s name.

    If your database column name is an SQL reserved word, or contains characters that aren’t allowed in Python variable names – notably, the hyphen – that’s OK. Django quotes column and table names behind the scenes.


    5.db_index
    Field.db_index
    If True, a database index will be created for this field.


    6.db_tablespace
    Field.db_tablespace
    The name of the database tablespace to use for this field’s index, if this field is indexed. The default is the project’s DEFAULT_INDEX_TABLESPACE setting, if set, or the db_tablespace of the model, if any. If the backend doesn’t support tablespaces for indexes, this option is ignored.

    7.default
    Field.default
    The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

    The default can’t be a mutable object (model instance, list, set, etc.), as a reference to the same instance of that object would be used as the default value in all new model instances. Instead, wrap the desired default in a callable. For example, if you want to specify a default dict for JSONField, use a function:

    def contact_default():
    return {"email": "to1@example.com"}

    contact_info = JSONField("ContactInfo", default=contact_default)
    lambdas can’t be used for field options like default because they can’t be serialized by migrations. See that documentation for other caveats.

    For fields like ForeignKey that map to model instances, defaults should be the value of the field they reference (pk unless to_field is set) instead of model instances.

    The default value is used when new model instances are created and a value isn’t provided for the field. When the field is a primary key, the default is also used when the field is set to None.


    8.editable(可编辑的)
    Field.editable
    默认为True,如果为False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.

    9.error_messages
    Field.error_messages
    The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override.

    Error message keys include null, blank, invalid, invalid_choice, unique, and unique_for_date. Additional error message keys are specified for each field in the Field types section below.

    These error messages often don’t propagate to forms. See Considerations regarding model’s error_messages.


    10.help_text
    Field.help_text

    Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.

    Note that this value is not HTML-escaped in automatically-generated forms. This lets you include HTML in help_text if you so desire. For example:

    help_text="Please use the following format: <em>YYYY-MM-DD</em>."
    Alternatively you can use plain text and django.utils.html.escape() to escape any HTML special characters. Ensure that you escape any help text that may come from untrusted users to avoid a cross-site scripting attack.


    11.primary_key
    Field.primary_key
    如果True,这个字段是表中的主键
    If you don’t specify primary_key=True for any field in your model, Django will automatically add an AutoField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields.

    primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object.

    The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one.

    12.unique
    Field.unique
    如果True,这个字段在表单中必须唯一.

    This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a django.db.IntegrityError will be raised by the model’s save() method.

    This option is valid on all field types except ManyToManyField and OneToOneField.

    Note that when unique is True, you don’t need to specify db_index, because unique implies the creation of an index.


    13.unique_for_date
    Field.unique_for_date

    Set this to the name of a DateField or DateTimeField to require that this field be unique for the value of the date field.

    For example, if you have a field title that has unique_for_date="pub_date", then Django wouldn’t allow the entry of two records with the same title and pub_date.

    Note that if you set this to point to a DateTimeField, only the date portion of the field will be considered. Besides, when USE_TZ is True, the check will be performed in the current time zone at the time the object gets saved.

    This is enforced by Model.validate_unique() during model validation but not at the database level. If any unique_for_date constraint involves fields that are not part of a ModelForm (for example, if one of the fields is listed in exclude or has editable=False), Model.validate_unique() will skip validation for that particular constraint.

    14.unique_for_month
    Field.unique_for_month
    Like unique_for_date, 但要求月份唯一

    15.unique_for_year
    Field.unique_for_year
    Like unique_for_date and unique_for_month 要求年唯一

    16.verbose_name
    Field.verbose_name
    可视化字段名,

    17.validators(验证器)
    Field.validators
    为该字段运行运算器,
    A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces. See Verbose field names.


    18.Registering and fetching lookups

    Field implements the lookup registration API. The API can be used to customize which lookups are available for a field class, and how lookups are fetched from a field.

  • 相关阅读:
    java selenium (十) 操作浏览器
    java selenium (九) 常见web UI 元素操作 及API使用
    java selenium (六) XPath 定位
    正则表达式
    日志模板
    软件开发规范
    TCP协议的粘包现象和解决方法
    验证用户的合法性
    PythonDay16
    PythonDay15
  • 原文地址:https://www.cnblogs.com/cangshuchirou/p/9301134.html
Copyright © 2020-2023  润新知