Python - Django - ORM custom field type char

Field is used to store CharField verchar type defined in the database

Char type field requires custom code below:

FixedCharField class (models.Field): 
    "" "
    custom field class type char
    " ""
    DEF the __init __ (Self, MAX_LENGTH, args *, ** kwargs):
        self.max_length = MAX_LENGTH
        Super (FixedCharField, Self) .__ init__ (= max_length max_length, args *, ** kwargs)

    DEF db_type (Self, Connection):
        "" "
        field defines the type of database table generation of char, length value specified max_length
        " ""
        return 'char (% S)' % self.max_length

models.py:

Models django.db Import from 


class FixedCharField (models.Field): 
    "" " 
    from a field of type char class definition of 
    " "" 
    DEF the __init __ (Self, MAX_LENGTH, args *, ** kwargs): 
        self.max_length = MAX_LENGTH 
        Super ( FixedCharField, Self) .__ the init __ (max_length = max_length, * args, ** kwargs) 

    DEF db_type (Self, Connection): 
        "" " 
        field type defines generated database table of char, a length value max_length specified 
        " "" 
        return ' char (% S) '% self.max_length 


class the Person (models.Model): 
    id = models.AutoField (primary_key = True) # of increment primary key id 
    name = models.CharField (MAX_LENGTH = 32)  
    Sex = FixedCharField (= MAX_LENGTH 32,default = "Man") # Using the above-defined field of type char
    Age = models.IntegerField ( )
    birthday = models.DateField(auto_now_add=True)

Execute commands to update the database

 

Guess you like

Origin www.cnblogs.com/sch01ar/p/11285028.html