ORM for Django Web Development

ORM in Django

Object Relational Mapping (ORM) is to automatically persist objects in an object-oriented language program to a relational database by using metadata describing the mapping between objects and databases.

Reference documentation: https://docs.djangoproject.com/zh-hans/2.2/topics/db/models/

Django database configuration

# settings文件下
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql", # 这里可以根据实际情况修改,譬如换成oracle、PostgreSQL等
        "NAME": "数据库名称",  
        "USER": "用户名",
        "PASSWORD": "密码",
        "HOST": "数据库访问地址",
        "POST": 3306 # Mysql数据库默认使用3306
    }
}

Build model

The model contains important fields and behaviors of the stored data.
A model is mapped to a database table.

model example

from django.db import models

class Students(models.Model):
	  name = models.CharField(max_length=30) # CharField为字段类型,max_length 为字段参数选项
	  age = models.IntegerField()
	  gender = models.BooleanField()
	  cs = models.ForeignKey('ClassInfo', on_delete=models.DO_NOTHING)

class ClassInfo(modes.Modell):
	 title = models.CharField(max_length=30)

Execute, generate data table

python manage.py makemigrations
python manage.py migrate

Common fields

Types of description
AutoField Automatically growing IntegerField, usually do not need to specify, when not specified Django will automatically create an automatically growing attribute named id.
BooleanField Boolean field, the value is True or False.
NullBooleanField Support Null, True, False three values.
CharField (max_length = max length) String. The parameter max_length represents the maximum number of characters.
TextField Large text field, generally used when it exceeds 4000 characters.
IntegerField Integer
DecimalField(max_digits=None, decimal_places=None) Decimal floating point number. The parameter max_digits represents the total digits. The parameter decimal_places represents the number of decimal places.
FloatField Floating point number. Same parameters as above
DateField:([auto_now=False, auto_now_add=False]) date. 1) The parameter auto_now means that each time an object is saved, this field is automatically set to the current time, used for the "last modified" timestamp, it always uses the current date, and the default is false. 2) The parameter auto_now_add indicates that the current time is automatically set when the object is created for the first time. It is used to create the timestamp. It always uses the current date, and the default is false. 3) The parameters auto_now_add and auto_now are mutually exclusive, and an error will occur in combination.
TimeField Time and parameters are the same as DateField.
DateTimeField Date and time, the parameters are the same as DateField.
FileField Upload file field.
ImageField Inherited from FileField, to verify the uploaded content to ensure that it is a valid picture.

Field selection

Common options

Option name description
default Defaults. Set the default value.
primary_key If True, the field will become the primary key field of the model. The default value is False, which is generally used as an option for AutoField.
unique If True, this field must have a unique value in the table, the default value is False.
db_index If the value is True, an index will be created for this field in the table. The default value is False.
db_column The name of the field. If not specified, the name of the attribute is used.
null If it is True, it means that it is allowed to be empty, and the default value is False.
blank If True, the field is allowed to be blank, and the default value is False.

Relational table options

ForeignKey foreign key association

Generally, the ForeignKey field is set to the "many" side of the "one-to-many".
ForeignKey can be associated with other tables or with itself.

Option name description
to Set the table to be associated
to_field Set the fields of the table to be associated
related_name The field name used in the reverse operation is used to replace the 'table name_set' in the original reverse query
related_query_name The connection prefix used in the reverse query operation, used to replace the table name
on_delete When deleting data in an associated table, the behavior of the current table and its associated rows.
db_constraint Whether to create foreign key constraints in the database, the default is True.
  • on_delete optional
Option name description
models.CASCADE Delete the associated data and delete the associated data
models.DO_NOTHING Delete the associated data, throw an error IntegrityError

models.PROTECT:删除关联数据,引发错误ProtectedError
models.SET_NULL:删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空)
models.SET_DEFAULT:删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值)
models.SET|删除关联数据,. 与之关联的值设置为指定值或者可执行对象的返回值,设置:models.SET(值)

ManyToManyField多对多

用于表示多对多的关联关系,在数据库中通过第三张表来建立关联关系。

选项名 描述
to 设置要关联的表
related_name 反向操作时,使用的字段名,用于代替原反向查询时的’表名_set’
related_query_name 反向查询操作时,使用的连接前缀,用于替换表名
symmetrical 仅用于多对多自关联时,指定内部是否创建反向操作的字段。默认为True。
through 在使用ManyToManyField字段时,Django将自动生成一张表来管理多对多的关联关系,也支持手动创建第三张表,此时就需要通过through来指定第三张表的表名。
through_fields 设置关联的字段。
db_table 默认创建第三张表时,数据库中表的名称。

DatetimeField、DateField、TimeField特有参数

选项名 描述
auto_now_add 配置auto_now_add=True,创建数据记录的时候会把当前时间添加到数据库。
auto_now 配置上auto_now=True,每次更新数据记录的时候会更新该字段。
发布了21 篇原创文章 · 获赞 0 · 访问量 317

Guess you like

Origin blog.csdn.net/qq_38756978/article/details/105295845