djando2.2-django ORM concept, operating database through ORM

Catalogue of series articles

1, django ORM

1. Concept of ORM

  • django ORM concept:

    The full name of ORM is Object Relational Mapping. With it, django can operate the database through python code (convert it into sql statement at the bottom), eliminating the writing of sql statement.

    However, due to the high degree of abstraction, the execution efficiency of sql statements is relatively low. Therefore, in some cases, we still need to write sql statements ourselves.

  • Mapping relationship:

    ORM converts python code into sql statements through the following correspondence:

    pythonRelational database
    classsurface
    Class propertiesfield
    objectrecord
    Property value of the objectField value of the record

2. Model writing

The Model class is the python class used to map database tables. It must be written in the models.py file and inherit the Model class.

For example, the following User class is a model class.

from django.db import models

class User(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=20)
    password = models.IntegerField()

The above python code is equivalent to the following MySQL Code:

BEGIN;
--
-- Create model User
--
CREATE TABLE `app01_user` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `username` varchar(20) NOT NULL, `password` integer NOT NULL);
COMMIT;

But at this time, we just wrote down the python code, and the database has not changed. If you want the code to take effect, you need to migrate.

3. Migrate

Execute the following two commands in the terminal in sequence:

  1. Build migration:

    python manage.py makemigrations
    

    It checks for changes to the models.py file and generates a migration file. The path of this file is the app folder \ migrations \ numeric prefix_ xxxxx.py.

  2. Perform migration:

    python manage.py migrate
    

    The command migrate will only be in installed_ The app registered in apps migrates the database and really applies the model to the database.
    The table name in the database is: app name_ The lowercase form of the model class.

  • View the corresponding SQL statement:
    Execute the following command to print the corresponding sql statement:

    python manage.py sqlmigrate app Name the numeric prefix of the migration file name
    

Note: every time you modify a model class, you must migrate it!!!

4. Common parameters of field class

Class attributes in the model class are instance objects of some Field classes, and these Field classes must master the following parameters:

  • primary_key = 'Boolean value':

    It is used to define the primary key. If we do not define the class attribute corresponding to the primary key when defining the model class, django will automatically create a primary key field named id for us.

  • max_length = 'Integer':
    Specify the field width. This parameter must be passed in by CharField class, otherwise an error will be reported.

  • verbose_name = 'alias':

    It is used to give the field a more straightforward alias (which can be in Chinese). In the django management background, the field will be displayed as an alias.

  • null = 'Boolean value': set whether the field can be empty.

  • Default = 'default value': sets the default value of the field.

2, Operate the database through ORM

ORM cannot operate the library, so we need to complete the creation, modification and deletion of the library through other methods.

1. Create data table

It is the writing of model classes, which has been mentioned above.

2. Addition, deletion and modification of fields

  • New fields:

    First add class attributes in the model class, and then perform the migration. The migration process may prompt:

    Please select a fix:
     1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
     2) Quit, and let me add a default in models.py
    Select an option:
    

    This is because no default value is set for this field or the field is allowed to be empty. sure:

    Enter 1, and then provide a default value to django: django will automatically help us set this value as the default value of this field;

    Input 2: stop generating the migration file, the developer to the model class, set the default value or allow it to be empty, and then migrate again.

  • Modify field:

    Directly modify the code in the model class and then migrate it.

  • Delete field:

    Directly annotate or delete the class attribute code, and then migrate it.

    If the class attribute of the model class is deleted, the data of the corresponding field will be lost after the migration. So be careful, it's best to check the code before migration!!!

3. Addition, deletion, modification and query of records

Data addition, deletion, modification and query should usually be written in the view. If you are just testing, you can use django's shell interaction environment:

python manage.py shell

Then you can import the required modules for testing. The following commands can be allowed in the shell, but you need to import the corresponding model classes first.

  • New record:

    Method 1:

    models.Model class name.object.create(attribute=value,......)
    

    Method 2:

    object = models.Model class name(attribute=value,......)  # Generate object
     object.save()  # Save to database
    
  • Query a single record:

    Query set = models.Model class name.object.filter(attribute=value,......)
    

    The filter method is equivalent to the WHERE clause of sql, and the return value of this method is the query set. Query set, also known as query result set and QuerySet, represents the collection of objects obtained from the database. Therefore, you need to take out an object before you can get the specific value:

    object = Query set.first()  # Get first object
     value = object.attribute  # Get value
    
  • Query all records:

    Method 1:

    Query set = models.Model class name.object.filter()  # Don't write any conditions
    

    Method 2:

    Query set = models.Model class name.object.all()
    

    Querying all records is usually to show to users. You can use the for statement of django template or jinja2 template. These template statements will be explained later.

  • Modification record:

    Method 1:

    Query set.update(attribute=value,......)
    

    update() modifies all records in the query set.

    Method 2:

    For example, hugh is an object of the User model class, that is, a record in the database

    hugh.attribute = value
    hugh.save()
    

    In the above method 2, when modifying the field value, all fields (including those that have not been modified) will be updated. Therefore, when there are many fields in the record, the efficiency will be very low.

  • Delete record:

    models.Model class name.object.filter(attribute=value,......).delete()
    

    In actual development, we usually do not really delete data, but perform logical deletion. That is, by adding an is to the table_ The boolean type field of delete, which is used to identify whether a piece of data has been deleted. Is of the data to be deleted_ Changing delete to 1 means that the field is "deleted".

4. ORM establishes table relationship

Usually we create a table first and then add foreign key fields, so we create other parts of the table first.

Take books, authors and publishing houses as an example, assuming that books and authors are many to many, books and publishing houses are many to one, details of authors and authors are one to one, and authors and publishing houses have no relationship:

from django.db import models

# Create your models here.

class Book(models.Model):
    """Book model class"""
    title = models.CharField(max_length=128)
    # Price field, 8 digits in total, with two decimal places
    price = models.DecimalField(max_digits=8, decimal_places=2)

class Author(models.Model):
    """Author model class"""
    name = models.CharField(max_length=32)

class Publisher(models.Model):
    """Publishing house model class"""
    name = models.CharField(max_length=32)

class AuthorDetail(models.Model):
    """Author details model class"""
    addr = models.CharField(max_length=128)
  • one-on-one:

    The author and author details are a one-to-one relationship. Foreign keys can be established on either side, but it is recommended to be established on the side with high query frequency.

    class Author(models.Model):
        """Author model class"""
        ......
        author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)
    

    If no field is specified, it is associated with the primary key field of author details by default. To specify a field can be used_ Field = 'associated field' parameter.

    on_delete=models.CASCADE parameter, used to set the deletion method of foreign key records. When data is deleted, the data associated with it will also be deleted.

  • One to many:

    The relationship between books and publishers is many to one, and the foreign key is established in the * * "many" party * *, that is, the book table.

    class Book(models.Model):
        """Book model class"""
    	......
        publisher = models.ForeignKey(to='Publisher', on_delete=models.CASCADE)
    

    If no field is specified, it is associated with the primary key field of the publishing house by default.

  • Many to many:

    The relationship between books and authors is many to many. You should create a new relationship table and establish foreign keys in the relationship table. However, ORM has been optimized, and it will automatically help us create relational tables. Therefore, we don't need to create relational tables manually. The foreign key field can be established on either side, but it is recommended to establish it on the side with high query frequency.

    class Book(models.Model):
        """Book model class"""
    	......
        author = models.ManyToManyField(to='author')
    

    In many to many relationships, you do not need to set on_delete parameter.

The field names generated by ForeignKey and OneToOneField will be automatically added with one_ ID suffix, that is, the field name of publisher attribute in the database is publisher_id.

In the Django 1. X version, you do not need to pass in on_ The delete parameter is CASCADE delete CASCADE by default. Other deletion methods will be explained later.

Tags: Python Web Development Database MySQL Django

Posted on Sat, 18 Sep 2021 14:44:06 -0400 by stephenk