Django common parameters and fields

Posted by Altairzq on Sun, 02 Jan 2022 04:30:18 +0100

Common fields and parameters

 

1 ORM field

AutoField

int auto increment column, the parameter primary must be filled in_ key=True. If there is no auto increment column in the model, a column named id will be automatically created.

IntegerField

An integer type ranging from - 2147483648 to 2147483647.

CharField

Character type, Max must be provided_ Length parameter, max_length indicates the character length.

DateField

Date field, date format: YYYY-MM-DD, equivalent to datetime in Python Date() instance.

DateTimeField

Date time field, format yyyy-mm-dd HH: mm [: SS [. Uuuuuuuuuuuu]] [TZ], equivalent to datetime in Python Datetime() instance

 

Common and non common fields

 

AutoField(Field)
        - int Auto increment column, parameter must be filled in primary_key=True

    BigAutoField(AutoField)
        - bigint Auto increment column, parameter must be filled in primary_key=True

        Note: when model If there is no self incrementing column in, a column named id Columns of
        from django.db import models

        class UserInfo(models.Model):
            # Automatically create a column named id And is a self increasing integer column
            username = models.CharField(max_length=32)

        class Group(models.Model):
            # Custom Auto increment column
            nid = models.AutoField(primary_key=True)
            name = models.CharField(max_length=32)

    SmallIntegerField(IntegerField):
        - Small integer -32768 ~ 32767

    PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
        - Positive small integer 0 ~ 32767
    IntegerField(Field)
        - Integer column(Signed) -2147483648 ~ 2147483647

    PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
        - Positive integer 0 ~ 2147483647

    BigIntegerField(IntegerField):
        - Long integer(Signed) -9223372036854775808 ~ 9223372036854775807

    BooleanField(Field)
        - Boolean type

    NullBooleanField(Field):
        - Boolean value that can be empty

    CharField(Field)
        - Character type
        - Must provide max_length Parameters, max_length Represents the character length

    TextField(Field)
        - Text type

    EmailField(CharField): 
        - String type, Django Admin as well as ModelForm Authentication mechanism is provided in

    IPAddressField(Field)
        - String type, Django Admin as well as ModelForm Provide validation in IPV4 mechanism

    GenericIPAddressField(Field)
        - String type, Django Admin as well as ModelForm Provide validation in Ipv4 and Ipv6
        - Parameters:
            protocol,Used to specify Ipv4 or Ipv6, 'both',"ipv4","ipv6"
            unpack_ipv4, If specified as True,Then enter::ffff:192.0.2.1 When, it can be resolved to 192.0.2.1,To enable this function, you need to protocol="both"

    URLField(CharField)
        - String type, Django Admin as well as ModelForm Provide validation in URL

    SlugField(CharField)
        - String type, Django Admin as well as ModelForm Provides authentication support for letters, numbers, underscores, and connectors (minus signs)

    CommaSeparatedIntegerField(CharField)
        - String type, the format must be a comma separated number

    UUIDField(Field)
        - String type, Django Admin as well as ModelForm For UUID Format validation

    FilePathField(Field)
        - character string, Django Admin as well as ModelForm Provides the function of reading files under folders
        - Parameters:
                path,                      Folder path
                match=None,                Regular matching
                recursive=False,           Recursive folder below
                allow_files=True,          Allow file
                allow_folders=False,       Allow folder

    FileField(Field)
        - String, the path is saved in the database, and the file is uploaded to the specified directory
        - Parameters:
            upload_to = ""      Save path of uploaded file
            storage = None      Storage components, default django.core.files.storage.FileSystemStorage

    ImageField(FileField)
        - String, the path is saved in the database, and the file is uploaded to the specified directory
        - Parameters:
            upload_to = ""      Save path of uploaded file
            storage = None      Storage components, default django.core.files.storage.FileSystemStorage
            width_field=None,   Highly saved database field name (string) of the uploaded picture
            height_field=None   Width of uploaded picture saved database field name (string)

    DateTimeField(DateField)
        - date+Time format YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]

    DateField(DateTimeCheckMixin, Field)
        - Date format      YYYY-MM-DD

    TimeField(DateTimeCheckMixin, Field)
        - Time format      HH:MM[:ss[.uuuuuu]]

    DurationField(Field)
        - Long integer, time interval, in the database according to bigint Storage, ORM The value obtained in is datetime.timedelta type

    FloatField(Field)
        - float 

    DecimalField(Field)
        - 10 Hexadecimal decimal
        - Parameters:
            max_digits,Total decimal length
            decimal_places,Decimal length

    BinaryField(Field)
        - Binary type

 

 

2 ORM field parameters

null

Used to indicate that a field can be empty.

unique

If set to unique=True, the field must be unique in this table.

db_index

If db_index=True means that the index is set for this field.

default

Set the default value for this field.

DateField and DateTimeField

auto_now_add

Configure auto_now_add=True, the current time will be added to the database when creating the data record.

auto_now

Configure auto on_ Now = true, this field will be updated every time the data record is updated.

 

3 Relationship fields

ForeignKey

The foreign key type is used to represent the foreign key association relationship in ORM. Generally, the ForeignKey field is set on the "many" side of "one to many".

ForeignKey can be associated with other tables and itself.

to

Sets the table to associate

to_field

Set the fields of the table to associate

related_name

The field name used in reverse operation is used to replace the 'table name' in the original reverse query_ set'.

The following is an example

null                Can fields in the database be empty
    db_column           Column names of fields in the database
    db_tablespace
    default             Default values for fields in the database
    primary_key         Is the field in the database a primary key
    db_index            Can fields in the database be indexed
    unique              Can fields in the database be uniquely indexed
    unique_for_date     Can a unique index be created for the [date] field in the database
    unique_for_month    Can a unique index be created for the [month] field in the database
    unique_for_year     Can a unique index be created for the [year] field in the database

    verbose_name        Admin Field names displayed in
    blank               Admin Allow user input to be blank in
    editable            Admin Can I edit in
    help_text           Admin Prompt for this field in
    choices             Admin The contents of the selection box are displayed in, and the unchanged data is placed in memory, so as to avoid cross table operation
                        For example: gf = models.IntegerField(choices=[(0, 'He Sui'),(1, 'Cousin '),],default=1)

    error_messages      Customize the error information (Dictionary type), so as to customize the error information to be displayed;
                        Dictionary key: null, blank, invalid, invalid_choice, unique, and unique_for_date
                        For example:{'null': "Cannot be empty.", 'invalid': 'Format error'}

    validators          Customize error validation (list type) to customize the desired validation rules
                        from django.core.validators import RegexValidator
                        from django.core.validators import EmailValidator,URLValidator,DecimalValidator,\
                        MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
                        For example:
                            test = models.CharField(
                                max_length=32,
                                error_messages={
                                    'c1': 'Priority error message 1',
                                    'c2': 'Priority error message 2',
                                    'c3': 'Priority error message 3',
                                },
                                validators=[
                                    RegexValidator(regex='root_\d+', message='Wrong', code='c1'),
                                    RegexValidator(regex='root_112233\d+', message='Wrong again', code='c2'),
                                    EmailValidator(message='Wrong again', code='c3'), ]
                            )

 

 

3 Relationship fields

ForeignKey

The foreign key type is used to represent the foreign key association relationship in ORM. Generally, the ForeignKey field is set on the "many" side of "one to many".

ForeignKey can be associated with other tables and itself.

to

Sets the table to associate

to_field

Set the fields of the table to associate

related_name

The field name used in reverse operation is used to replace the 'table name' in the original reverse query_ set'.

 

 

related_query_name

The join prefix used in the reverse query operation, which is used to replace the table name.

on_delete

When data in an associated table is deleted, the behavior of the current table and its associated rows.

  models.CASCADE
Delete the associated data and delete the associated data


  models.DO_NOTHING
Deleting associated data raises an error integrity error


  models.PROTECT
Deleting associated data raises the error ProtectedError


  models.SET_NULL
Delete the associated data and set the associated value to null (provided that the FK field needs to be set to nullable)


  models.SET_DEFAULT
Delete the associated data and set the associated value as the default value (provided that the FK field needs to be set as the default value)


  models.SET

Delete associated data,
a. set the associated value to the specified value, setting: models Set (value)

 

db_constraint

Whether to create a foreign key constraint in the database. The default is True.

 

OneToOneField

One to one field.

Usually, one-to-one fields are used to extend existing fields.

The one-to-one association relationship is often used when the query frequency difference between different fields in a table is too large. The fields that could have been stored in one table are disassembled and placed in two tables, and then the two tables establish a one-to-one association relationship.

 

to

Set the table to associate.

to_field

Set the fields to associate.

on_delete

Same as ForeignKey field.

ManyToManyField

Used to represent many to many relationships. In the database, the association relationship is established through the third table

to

Sets the table to associate

related_name

Same as ForeignKey field.

related_query_name

Same as ForeignKey field.

symmetrical

It is only used to specify whether to create a reverse operation internally when many to many Auto Association. The default is True.

 

through

When using the ManyToManyField field, Django will automatically generate a table to manage many to many relationships.

However, we can also manually create the third table to manage the many to many relationship. At this time, we need to specify the table name of the third table through through.

through_fields

Set the associated field.

db_table

The name of the table in the database when the third table is created by default.