(3) Orm of Django web development

Time:2021-6-5

Orm in Django

Object relational mapping (ORM) is to automatically persist objects in object-oriented language programs to relational databases by using metadata describing the mapping between objects and databases.

Reference documents:https://docs.djangoproject.co…

Django database configuration

#Settings file
DATABASES = {
    "default": {
        "Engine": "Django. DB. Backends. MySQL", which can be modified according to the actual situation, such as Oracle, PostgreSQL, etc
        "Name": "database name,",  
        "User": user name,
        "Password": "password":,
        "Host": database access address,
        "Post": 3306 # MySQL database uses 3306 by default
    }
}

Building a model

Model contains important fields and behaviors of stored data.
A model maps to a database table.

Model example

from django.db import models

class Students(models.Model):
      name = models.CharField(max_ Length = 30) # charfield is the field type, max_ Length is the field parameter option
      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 and generate data table

python manage.py makemigrations
python manage.py migrate

Common fields

type describe
AutoField The auto growing integerfield is usually not specified. If it is not specified, Django will automatically create an auto growing attribute named ID.
BooleanField Boolean field with a value of true or false.
NullBooleanField Null, true and false values are supported.
CharField(max_ Length = maximum length) character string. Parameter Max_ Length represents the maximum number of characters.
TextField Large text field, generally more than 4000 characters.
IntegerField integer
DecimalField(max_digits=None, decimal_places=None) Decimal floating point number. Parameter Max_ Digits is the total number of bits. Parameter decimal_ Places is the number of decimal places.
FloatField Floating point number. The parameters are the same as above
DateField:([auto_now=False, auto_now_add=False]) Date. 1) Parameter auto_ Now means that each time an object is saved, this field is automatically set to the current time, which is used for the “last modification” timestamp. It always uses the current date, and the default is false. 2) Parameter auto_ now_ Add indicates that the current time is automatically set when the object is first created. It is used to create a timestamp. It always uses the current date. The default is false. 3) Parameter auto_ now_ Add and auto_ Now is mutually exclusive, the combination will be wrong.
TimeField The time and parameter are the same as DateField.
DateTimeField Date time, the same as DateField.
FileField Upload file field.
ImageField Inherited from filefield, check the uploaded content to ensure it is a valid picture.

Field selection

Common options

Option name describe
default Default value. Set the default value.
primary_key If it is true, the field will become the primary key field of the model. The default value is false, which is generally used as an option of 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 is created for this field in the table, and the default value is false.
db_column The name of the field, or if not specified, the name of the property.
null If it is true, it means that it is allowed to be empty, and the default value is false.
blank If it is true, the field is allowed to be blank, and the default value is false.

Relationship 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 itself.

Option name describe
to Set the table to associate
to_field Set the fields of the table to associate
related_name In reverse operation, the field name is used to replace the table name in the original reverse query_ set’
related_query_name The connection prefix used in reverse query operation to replace the table name
on_delete The behavior of the current table and its associated rows when data in the associated table is deleted.
db_constraint Whether to create a foreign key constraint in the database. The default value is true.
  • on_ Delete optional
Option name describe
models.CASCADE Delete the associated data and delete the associated data
models.DO_NOTHING Deleting associated data raises an error integrityreror

Models.protect: delete associated data, causing an error protectederror
models.SET_ Null: delete the associated data and set the associated value to null (if FK field needs to be set to nullable)
models.SET_ Default: delete the associated data and set the associated value as the default value (if FK field needs to set the default value)
Models. Set | delete the associated data. The associated value is set to the specified value or the return value of the executable object. Set: models. Set (value)

Manytomanyfield many to many

It is used to represent the association relationship of many to many, and establish the association relationship through the third table in the database.

Option name describe
to Set the table to associate
related_name In reverse operation, the field name is used to replace the table name in the original reverse query_ set’
related_query_name The connection prefix used in reverse query operation to replace the table name
symmetrical For many to many self association only, specifies whether to create a reverse operation field internally. The default is true.
through When using the manytomanyfield field, Django will automatically generate a table to manage the many to many association relationship. It also supports the manual creation of the third table. In this case, you need to specify the table name of the third table 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.

Datetimefield, DateField, timefield specific parameters

Option name describe
auto_now_add  Configure Auto_ now_ Add = true, the current time will be added to the database when the data record is created.
auto_now Configure Auto_ Now = true, this field will be updated every time the data record is updated.