10 - model layer - common and non 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.date() instance in Python.

DateTimeField

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

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 self incrementing integer column with column name id
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
 Correspondence:
    'AutoField': 'integer AUTO_INCREMENT',
    'BigAutoField': 'bigint AUTO_INCREMENT',
    'BinaryField': 'longblob',
    'BooleanField': 'bool',
    'CharField': 'varchar(%(max_length)s)',
    'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
    'DateField': 'date',
    'DateTimeField': 'datetime',
    'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
    'DurationField': 'bigint',
    'FileField': 'varchar(%(max_length)s)',
    'FilePathField': 'varchar(%(max_length)s)',
    'FloatField': 'double precision',
    'IntegerField': 'integer',
    'BigIntegerField': 'bigint',
    'IPAddressField': 'char(15)',
    'GenericIPAddressField': 'char(39)',
    'NullBooleanField': 'bool',
    'OneToOneField': 'integer',
    'PositiveIntegerField': 'integer UNSIGNED',
    'PositiveSmallIntegerField': 'smallint UNSIGNED',
    'SlugField': 'varchar(%(max_length)s)',
    'SmallIntegerField': 'smallint',
    'TextField': 'longtext',
    'TimeField': 'time',
    'UUIDField': 'char(32)',

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 This means that the index is set for this field.

#### **default**

Set the default value for this field.

###  DateField and DateTimeField

#### auto_now_add

to configure auto_now_add=True,When creating a data record, the current time will be added to the database.

#### auto_now

Configuration auto_now=True,This field is updated each time the data record is updated.
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 to 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’.

For example:

class Classes(models.Model):
    name = models.CharField(max_length=32)

class Student(models.Model):
    name = models.CharField(max_length=32)
    theclass = models.ForeignKey(to="Classes")

When we want to query all the students associated with a class (reverse query), we will write this:

models.Classes.objects.first().student_set.all()

When we add the parameter related in the ForeignKey field_ After name,

class Student(models.Model):
    name = models.CharField(max_length=32)
    theclass = models.ForeignKey(to="Classes", related_name="students")

When we want to query all the students associated with a class (reverse query), we will write this:

models.Classes.objects.first().students.all()

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 value associated with it to the specified value, setting: models.set (value)
b. the value associated with it is set as the return value of the executable object. Setting: models.set (executable object)

def func():
    return 10

class MyModel(models.Model):
    user = models.ForeignKey(
        to="User",
        to_field="id",
        on_delete=models.SET(func)
    )

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.

class Author(models.Model):
    name = models.CharField(max_length=32)
    info = models.OneToOneField(to='AuthorInfo')
    

class AuthorInfo(models.Model):
    phone = models.CharField(max_length=11)
    email = models.EmailField()

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.

for instance:

class Person(models.Model):
    name = models.CharField(max_length=16)
    friends = models.ManyToManyField("self")

At this point, the person object has no person_set property.

class Person(models.Model):
    name = models.CharField(max_length=16)
    friends = models.ManyToManyField("self", symmetrical=False)

At this point, the person object can now use person_ Use the set property to reverse the query.

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.

4 three ways of many to many Association

Method 1: create the third table by yourself

class Book(models.Model):
    title = models.CharField(max_length=32, verbose_name="title")


class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="Author's name")


# Create the third table by yourself and associate books and authors through foreign keys respectively
class Author2Book(models.Model):
    author = models.ForeignKey(to="Author")
    book = models.ForeignKey(to="Book")

    class Meta:
        unique_together = ("author", "book")

Method 2: automatically create the third table through ManyToManyField

class Book(models.Model):
    title = models.CharField(max_length=32, verbose_name="title")


# Automatically create the third table through the ManyToManyField provided by ORM
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="Author's name")
    books = models.ManyToManyField(to="Book", related_name="authors")

Method 3: set ManyTomanyField and specify the third self created table

class Book(models.Model):
    title = models.CharField(max_length=32, verbose_name="title")


# Create the third table by yourself and specify the association through ManyToManyField
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="Author's name")
    books = models.ManyToManyField(to="Book", through="Author2Book", through_fields=("author", "book"))
    # through_fields accepts a 2-tuple ('field1 ',' field2 '):
    # Where field1 is the name of the foreign key of the model defining ManyToManyField (author), and field2 is the name of the foreign key of the associated target model (book).


class Author2Book(models.Model):
    author = models.ForeignKey(to="Author")
    book = models.ForeignKey(to="Book")

    class Meta:
        unique_together = ("author", "book")

be careful:

The third method is used when we need to store additional fields in the third relational table.

However, when we use the third method to create many to many relationships, we cannot use the methods of set, add, remove and clear to manage many to many relationships. We need to manage many to many relationships through the model of the third table.

5 yuan Information

The class corresponding to ORM contains another Meta class, which encapsulates some database information. The main fields are as follows:

db_table

The table name of ORM in the database is app by default_ Class name, which can be passed through db_table can override the table name.

index_together

Union index.

unique_together

Federated unique index.

ordering

Specifies what fields are sorted by default.

Only when this property is set can the query result be reversed ().

class UserInfo(models.Model):
    nid = models.AutoField(primary_key=True)
    username = models.CharField(max_length=32)

    class Meta:
        # Table names generated in the database default app name + underscore + class name
        db_table = "table_name"

        # Joint index
        index_together = [
            ("pub_date", "deadline"),
        ]

        # Federated unique index
        unique_together = (("driver", "restaurant"),)
        
        ordering = ('name',)
        
        # Table name displayed in admin
        verbose_name='ha-ha'

        # verbose_name plus s
        verbose_name_plural=verbose_name

6 custom fields (understand)

Custom char type fields:

class FixedCharField(models.Field):
    """
    Custom char Field class of type
    """
    def __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):
        """
        The field type of the restricted generated database table is char,Count Reg max_length Specified value
        """
        return 'char(%s)' % self.max_length


class Class(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=25)
    # Use custom char type fields
    cname = FixedCharField(max_length=25)

Posted on Fri, 03 Dec 2021 06:41:10 -0500 by jingcleovil