Common fields and parameters

Common Fields

Auto Field

int auto increment, must fill in the parameters primary_key=True. When the model, if there is no auto-increment, then automatically creates a column called id columns.

IntegerField

An integral type, range -2147483648 ~ 2147483647.

CharField

Character type, must provide a max_lengthparameter, representing the character length MAX_LENGTH.

DateField

Date field, the date format YYYY-MM-DD, corresponding to the Python datetime.date()instance.

DateTimeField

Date time field format YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ], corresponding to the Python datetime.datetime()instance.

Fields Collection

AutoField(Field)
    - int自增列,必须填入参数 primary_key=True

BigAutoField(AutoField)
    - bigint自增列,必须填入参数 primary_key=True

    注:当model中如果没有自增列,则自动会创建一个列名为id的列
        from django.db import models

        class UserInfo(models.Model):
            # 自动创建一个列名为id的且为自增的整数列
            username = models.CharField(max_length=32)

        class Group(models.Model):
            # 自定义自增列
            nid = models.AutoField(primary_key=True)
            name = models.CharField(max_length=32)

SmallIntegerField(IntegerField):
    - 小整数 -32768 ~ 32767

PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
    - 正小整数 0 ~ 32767
IntegerField(Field)
    - 整数列(有符号的) -2147483648 ~ 2147483647

PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
    - 正整数 0 ~ 2147483647

BigIntegerField(IntegerField):
    - 长整型(有符号的) -9223372036854775808 ~ 9223372036854775807

BooleanField(Field)
    - 布尔值类型

NullBooleanField(Field):
    - 可以为空的布尔值

CharField(Field)
    - 字符类型
    - 必须提供max_length参数, max_length表示字符长度

TextField(Field)
    - 文本类型

EmailField(CharField):
    - 字符串类型,Django Admin以及ModelForm中提供验证机制

IPAddressField(Field)
    - 字符串类型,Django Admin以及ModelForm中提供验证 IPV4 机制

GenericIPAddressField(Field)
    - 字符串类型,Django Admin以及ModelForm中提供验证 Ipv4和Ipv6
    - 参数:
        protocol,用于指定Ipv4或Ipv6, 'both',"ipv4","ipv6"
        unpack_ipv4, 如果指定为True,则输入::ffff:192.0.2.1时候,可解析为192.0.2.1,开启此功能,需要protocol="both"

URLField(CharField)
    - 字符串类型,Django Admin以及ModelForm中提供验证 URL

SlugField(CharField)
    - 字符串类型,Django Admin以及ModelForm中提供验证支持 字母、数字、下划线、连接符(减号)

CommaSeparatedIntegerField(CharField)
    - 字符串类型,格式必须为逗号分割的数字

UUIDField(Field)
    - 字符串类型,Django Admin以及ModelForm中提供对UUID格式的验证

FilePathField(Field)
    - 字符串,Django Admin以及ModelForm中提供读取文件夹下文件的功能
    - 参数:
        path,                      文件夹路径
        match=None,                正则匹配
        recursive=False,           递归下面的文件夹
        allow_files=True,          允许文件
        allow_folders=False,       允许文件夹

FileField(Field)
    - 字符串,路径保存在数据库,文件上传到指定目录
    - 参数:
        upload_to = ""      上传文件的保存路径
        storage = None      存储组件,默认django.core.files.storage.FileSystemStorage

ImageField(FileField)
    - 字符串,路径保存在数据库,文件上传到指定目录
    - 参数:
        upload_to = ""      上传文件的保存路径
        storage = None      存储组件,默认django.core.files.storage.FileSystemStorage
        width_field=None,   上传图片的高度保存的数据库字段名(字符串)
        height_field=None   上传图片的宽度保存的数据库字段名(字符串)

DateTimeField(DateField)
    - 日期+时间格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]

DateField(DateTimeCheckMixin, Field)
    - 日期格式      YYYY-MM-DD

TimeField(DateTimeCheckMixin, Field)
    - 时间格式      HH:MM[:ss[.uuuuuu]]

DurationField(Field)
    - 长整数,时间间隔,数据库中按照bigint存储,ORM中获取的值为datetime.timedelta类型

FloatField(Field)
    - 浮点型

DecimalField(Field)
    - 10进制小数
    - 参数:
        max_digits,小数总长度
        decimal_places,小数位长度

BinaryField(Field)
    - 二进制类型

Correspondence between the field and the actual database fields

对应关系:
    '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)',

Field parameters

null: used to represent a field can be empty.

unique: If set to unique=Truethe field table must be unique.

db_index: If db_index=Trueyou set up the database represents the index for this field.

default: Sets the default value for the field.

Unique time field

DatetimeField, DateField, TimeField this three time fields, properties can be set as follows.

auto_now_add: configuration auto_now_add=True, data record is created when the current time will be added to the database.

auto_now: configuration auto_now=True, each time updating the data record will update the field.

Relationship field

ForeignKey

Foreign key is used to indicate the type of the foreign key relationship in the ORM, generally the ForeignKey many fields provided in the "many" side.

ForeignKey can make tables and other relationships at the same time and can also make their relationship.

Field parameters

to: Set the table to be associated

to_field: Sets the table associated field

related_name: reverse operation, the use of field names, for the "table _set" instead of the original when the reverse lookup.

E.g:

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 you want to query a class association of all students (reverse lookup), you would write:

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

When a parameter is added in related_name ForeignKey field,

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

When you want to query a class association of all students (reverse lookup), you would write:

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

related_query_name: reverse query operation, connected prefix that replaces the table name.

on_delete: When you delete data associated with the table, the behavior of the current table associated with the line.

models.CASCADE: delete the associated data, also associated with deleted

models.DO_NOTHING: delete the associated data, causing errors IntegrityError

models.PROTECT: delete the associated data, causing errors ProtectedError

models.SET_NULL: delete the associated data, the value associated therewith is null (the precondition FK field should be set to be empty)

models.SET_DEFAULT: delete the associated data (premise FK fields need to set the default value) associated with the value set to default values

models.SET: delete the associated data
a value associated with the specified value, provided:. models.SET (value)
. B value associated with the return value for the executable object is provided: models.SET (available execution 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 field. Usually one field to extend the existing field.

Example:

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()

Field parameters

to: Set the table to be associated.

to_field: Set field to be associated.

on_delete: with ForeignKey field.

ManyToManyField

Used to represent the relationship many to many. In the database to establish relationships through the third table.

Field parameters

to: Set the table to be associated

related_name: with ForeignKey field.

related_query_name: with ForeignKey field.

symmetrical: only for self-many association, specify whether to create a field inside the reverse operation. The default is True.

for example:

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

In this case, person object is not person_set property.

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

In this case, person objects can now use a reverse lookup person_set attributes.

through: When using ManyToManyField field, Django will automatically generate a table to manage many to many relationship. But also can manually create a third table to manage many relationships, then you need throughto specify the table name the third table.

through_fields: Set the associated field.

db_table: When you create a third table by default, the name of the database table.

Three ways-many association relationship

Create your own third table

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

class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="作者姓名")

# 自己创建第三张表,分别通过外键关联书和作者
class Author2Book(models.Model):
    author = models.ForeignKey(to="Author")
    book = models.ForeignKey(to="Book")

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

Automatically create a third table by ManyToManyField

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

# 通过ORM自带的ManyToManyField自动创建第三张表
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="作者姓名")
    books = models.ManyToManyField(to="Book", related_name="authors")

Set ManyTomanyField and specify the third table-created

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

# 自己创建第三张表,并通过ManyToManyField指定关联
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="作者姓名")
    books = models.ManyToManyField(to="Book", through="Author2Book", through_fields=("author", "book"))
    # through_fields接受一个2元组('field1','field2'):
    # 其中field1是定义ManyToManyField的模型外键的名(author),field2是关联目标模型(book)的外键名。

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

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

Note: When the additional fields need to be stored in the third table, and use a third way. But when you create a third way to use-many relationship, you can not use the set, add, remove, clear way to manage many relationships, and the need to manage many relationships through third model table.

Meta-information

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

db_table: ORM table name in the database default app is the class name, you can db_table can override the table name.

index_together: joint index.

unique_together: United unique index.

ordering: specify the default sort by any field. Only set this property to query the results can be reverse().

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

        class Meta:
            # 数据库中生成的表名称 默认 app名称 + 下划线 + 类名
            db_table = "table_name"

            # 联合索引
            index_together = [
                ("pub_date", "deadline"),
            ]

            # 联合唯一索引
            unique_together = (("driver", "restaurant"),)
            
            ordering = ('name',)
            
            # admin中显示的表名称
            verbose_name='哈哈'

            # verbose_name加s
            verbose_name_plural=verbose_name

Guess you like

Origin www.cnblogs.com/qiuxirufeng/p/11543961.html