M in MTV stands for Model. A Django Model is a description of data in a database using Python code. It is the structure of data and is equivalent to the CREATE Table statement in SQL.

Understand the ORM

The ORM: Object Relational Mapping(ORM) is an important part of Django. An important part of MVC framework is ORM. It decoupled the data model from the database, that is, the design of the data model does not depend ona specific database. Databases can be easily replaced with a simple configuration.

The main tasks of ORM are:

  • Generate a table structure based on the type of the object
  • Convert object and list operations into SQL statements
  • Convert SQL query results into objects and lists

Create project & Configure database

When the project is created, open the setting.py configuration file and find out that DATABASES uses SQlite3 by default. If you need to change to another database, you only need to change this area. Actually the django. Db. Backends. Also django provides good below the sqlite3, can look up in the installation path to, C:\Users\Administrator\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\db\backends

SQL > alter database configuration to link to mysql database, set setting.

The DATABASES = {' default ': {' ENGINE' : 'the django. Db. Backends. Mysql', 'NAME' : 'test', 'USER' # to connect to the database NAME: 'root', # login account 'PASSWORD': '123456', # login PASSWORD' HOST': 'localhost', # database server IP: '3306', # port, default 3306}}Copy the code

The development process

  1. Define a Model class in models.py that inherits from models.model
  2. Add the app to installed_app in settings.py
  3. Generate migration files
  4. Perform migration to generate tables
  5. Use model classes for CRUD operations

Create an

A project can contain multiple applications. Run the python manage.py startApp test1app command to create an application

MySQLdb = MySQLdb = MySQLdb = MySQLdb = MySQLdb = pymysql = MySQLdb PIP install pymysql. If pyhton is 2.x, install PIP install mysql-python.

After all the templates are installed successfully, add the following to the __init__.py file in 3.x:

import pymysql
pymysql.install_as_MySQLdb()
Copy the code

In this case, you can create the application successfully by executing the statement of creating the application. After the application is successfully created, add the created application in setting.py. INSTALLED_APPS stands for Django active applications. The last one is the one we added manually. These are the default active applications in Django.

INSTALLED_APPS = ('django.contrib.admin',# admin' django.contrib.auth', # authentication systems' django. Contrib. Contenttypes', # content type frame 'django. Contrib. Sessions', #' django. Contrib. The messages' session frame, frame # news 'django. Contrib. Staticfiles', # management framework of static files' test1' # the application of the newly added)Copy the code

Define the model

When attributes are defined in a model, django generates fields in the table. Django adds auto-growing primary key columns to the table. Each model can have only one primary key column, and if you specify a primary key column, Django does not regenerate it.

Attribute naming:

  1. Cannot be a Python keyword
  2. Because of the way Django queries are, consecutive underscores are not allowed

The field types are defined in django.db.models. Fields and imported into django.db.models for ease of use

Usage: Db import models From Django. db import models Create an object with a Field type of models.Field, assign the value to the property, and perform logical deletion of all important data. The default value is False

Field type:

  • AutoField: An IntegerField that grows automatically based on the actual ID. It is usually not specified

If not specified, a primary key field is automatically added to the model

  • BooleanField: True /false field for which the default form control is CheckboxInput
  • NullBooleanField: Supports null, true, and false values
  • CharField(max_length= character length) : string. The default form style is TextInput
  • TextField: large TextField, usually used over 4000. The default form control is Textarea
  • IntegerField: integer
  • DecimalField(max_digits=None, decimal_places=None) : Decimal floating point number represented using python’s Decimal instance
  • Decimalfield. max_digits: Total number of digits
  • DecimalField. Decimal_places: Number of digits after the decimal point
  • FloatField: A floating-point number represented by a Float instance of Python
  • DateField[auto_now=False, auto_now_add=False]) : the date represented by Python’s datetime.date instance

Parameter datefield. auto_now: Automatically sets this field to the current time each time an object is saved, which is used for the “last modified” timestamp, which always uses the current date and defaults to false. Parameter datefield. auto_now_add: The current time is automatically set when the object is first created. The timestamp used for creation, which always uses the current date, defaults to false. The default corresponding form control for this field is a TextInput. Added a calendar control written in JavaScript to the admin site, a “Today” shortcut button, and an additional invalid_date error message key auto_now_add, auto_now, and default. These Settings are mutually exclusive. Any combination between them will have the wrong result

  • TimeField: The time represented using Python’s datetime.time instance, with the same argument as DateField
  • DateTimeField: The date and time represented using Python’s datetime.datetime instance, with the same arguments as DateField
  • FileField: a field used to upload files
  • ImageField: Inherits all the properties and methods of FileField, but verifies the uploaded object to make sure it is a valid image

Field options: Field options allow constraints on fields (specified by keyword arguments in the case of field objects)

  • Null: If True, Django stores null values to the database as null. The default value is False
  • Blank: This field is allowed to be blank if True. The default is False
  • Contrast: NULL is a database category, blank is a form validation category
  • Db_column: Specifies the name of the field. If not specified, the name of the property is used
  • Db_index: If True, an index will be created for this field in the table
  • Default: indicates the default value
  • Primary_key: If True, this field becomes the primary key field of the model
  • Unique: If True, this field must have a unique value in the table

The types of relationships include:

  • ForeignKey: One-to-many, which defines fields in the many end
  • ManyToManyField: Many-to-many, defining fields on both ends
  • OneToOneField: One to one, the field is defined on either end

Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Meta Object’s default sort field, used when getting a list of objects that receive a list of attributes

class BookInfo(models.Model): btitle=models.CharField(max_length=20) bpub_date=models.DateTimeField() bread=models.IntegerField(default=0) bcommet=models.IntegerField(default=0) isDelete=models.BooleanField(default=False) class Meta: Db_table ="bookinfo" orderings =['id'] # orderingdb_table ="bookinfo" orderings =['-id'] # orderingdb_table ="bookinfo" orderings =['-id'Copy the code

Once you have some information about the properties in the model class, start defining two model classes. Find Model.py in the created application and write the model class:

from django.db import models # Create your models here. class BookInfo(models.Model): btitle=models.CharField(max_length=20) bpub_date=models.DateTimeField() bread=models.IntegerField(default=0) bcommet=models.IntegerField(default=0) isDelete=models.BooleanField(default=False) class Meta: db_table="bookinfo" class HeroInfo(models.Model): hname=models.CharField(max_length=20) hgender=models.BooleanField(default=True) isDelete=models.BooleanField(default=True) hcontent=models.CharField(max_length=100) hbook=models.Foreignkey('BookInfo') Set the foreign keyCopy the code

Generate migration

Once the model is defined and validated, run the following command to tell Django that you made changes to the model (build migration). Django stores the changes to the model in migration, which is a file on disk.

Names, Hoisting Django tell Django what changes have been made to the model, and Django generates a file named 0001_initial.py under migrations. This file names changes made to the model

Python manage. Py sqlMigrate test1app 0001 Python Manage. Py sqlMigrate test1app 0001 Python Manage

If you don’t understand SQL, you’ll notice that the generated tables differ from the ones we defined, starting with the following explanatory points: Table names are generated automatically by combining app names (polls) with lowercase model names — question and choice primary keys (ids) are added automatically. (You can also override this behavior.) By convention, Django adds “_id” after the field name of a foreign key. (Yes, you can still override this behavior.) FOREIGN KEY relationships are explicitly declared by FOREIGN KEY constraints. Never mind the DEFERRABLE part; It simply tells PostgreSQL not to perform the foreign key association until the end of the transaction. The sqlMigrate command does not actually run migration files on your database – it simply prints the SQL Django deems necessary on the screen so you can see it.

The next step is critical because the database has not been created yet, and the python Manage.py Migrate execution is performed by checking the files that have just been generated under Migrations to see what we need to do with the data and translate it

The migrate command will find all migration files that have not yet been applied (Django uses a special table in the database called django_migrations to track which migration files have been applied) and run them on your database — essentially, Synchronize your database schema with your modified model.

Migration is very powerful and allows you to constantly modify your model during development without deleting a database or table and then creating a new one – it focuses on upgrading your database without losing data

Three steps to model change: Modify your model (in the models.py file). Run Python Manage.py Makemigrations to create migration files for these changes and run Python Manage.py Migrate to update the changes to the database

Members of the model

Class properties, Objects: Are objects of type Manager that interact with the database. When you define a model class without specifying a Manager, Django provides a Manager named Objects for the model class

class BookInfo(models.Model):
    ...
    books = models.Manager()
Copy the code

When you specify a manager for a model class, Django no longer generates a default manager named Objects for the model class

The Manager is the interface through which djangos models perform database queries. Every model in a Django application has at least one Manager. Custom Manager classes are used in two ways: 1. Modify the original queryset returned by the manager: override the get_queryset() method

class BookInfoManager(models.Manager):
    def get_queryset(self):
        return super(BookInfoManager, self).get_queryset().filter(isDelete=False)
class BookInfo(models.Model):
    ...
    books = BookInfoManager()
Copy the code

DoesNotExist: this exception is raised when the object of the model DoesNotExist when making a single query, used with try/except

Instance method STR (self) : overwrites the object method, which is called when converting the object to a string Save () : Saves the model object to the table delete() : deletes the model object from the table

Model query

Calling the filter method on the manager returns a query set, which represents a collection of objects retrieved from the database. The query set can contain zero, one, or more filters that limit the results of the query based on the given parameters. From an Sql perspective, query sets are equivalent to SELECT statements, and filters are like WHERE and limit clauses

Lazy execution: Creating a query set does not bring any access to the database until the data is invoked

The method of returning the query set, called filter all() filter() exclude() order_by() values() : an object forms a dictionary and then returns a list