Django-model-field options

Field options

  • Each field accepts a set of field-related parameters (documented at Model Field Reference middle).  E.g, CharField (and its derived classes) require max_length parameter to specify the size of the VARCHAR database field.
  • Common parameters for all fields
    • null If True, Django will store empty values ​​as NULL in the database. Defaults to False.
    • blank If True, this field allows null values, default is False.
      Note that this is the same as null different. 
      null purely database category,Refers to whether the field content in the database is allowed to be empty,
      and blank It is the category of form data input validation.
      if a field blank=True,The validation of the form will allow a null value to be entered.
      if the field's blank=False,This field is required.
    • choices

      An iterable object (for example, a list or tuple) consisting of binary tuples used to provide choices for fields. If choices is set, the default form will be a select box instead of a standard text box, and the options of this select box are the options in choices.

      Here's an example with a choices list:

      YEAR_IN_SCHOOL_CHOICES = (
          ('FR', 'Freshman'),
          ('SO', 'Sophomore'),
          ('JR', 'Junior'),
          ('SR', 'Senior'),
          ('GR', 'Graduate'),
      )

      The first element in each tuple is the value that will be stored in the database. 
      The second element will be created by the default form widget or ModelChoiceField show. Given a model instance, the display value of the options field can be accessed using the get_FOO_display() method.  E.g:

      from django.db import models
      
      class Person(models.Model):
          SHIRT_SIZES = (
              ('S', 'Small'),
              ('M', 'Medium'),
              ('L', 'Large'),
          )
          name = models.CharField(max_length=60)
          shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
      >>> p = Person(name="Fred Flintstone", shirt_size="L")
      >>> p.save()
      >>> p.shirt_size
      'L'
      >>> p.get_shirt_size_display()
      'Large'

       

    • default The default value of the field. Can be a value or a callable object. If callable , it will be called every time a new object is created.
    • help_text Additional help content displayed by the form widget. It is useful for generating documentation even if the field is not used in the form.
    • primary_key If True, then this field is the primary key of the model.
      If you do not specify any of the fields primary_key=True
      Django will automatically add a IntegerField Fields are used as primary keys, so unless you want to override the default primary key behavior, there is no need to set either field's primary_key=True,

 

Tags: Django

Posted by Installer on Tue, 10 May 2022 23:08:10 +0300