Environment configuration: Ubuntu 16.04,django 1.8.2,mysql-python 1.2.5
The purpose is to understand the relationship between the definition of the model class and the table in its corresponding database.
Measured findings:
In relation to the table relationships in the model class and the database, the class attributes defined in the model class are used to build the table structure inside the database, like MySQL to create a table.
- A model class that corresponds to a table within the database.
- A class property that corresponds to a field in a database table
The type of a class property (such as Charfield), which corresponds to the field type in the database.
Python running into the Python manage.py shell
A shell environment that operates on a model class and its objects, similar to a table and a field. Note: The object does not invoke class properties, and Python also allows this. The following object's properties and class properties have the same name primarily for mapping, knowing where to add data to the table.
Add data to the table, INSERT statements like database tables
B = BookInfo()b.btitle = ‘abc b.save()
Modify table data, similar to a table update operation
B = BookInfo.objects.get(pk=1) pk是主键 primarykehy b.btitle =‘abc‘ b.save()
Query table
BookInfo.objects.all()
Delete a table
b.delete() BookInfo.objects.all() 查看结果
The test flow is as follows:
A virtual environment to create a project test4 and application Booktest, project test4 using the test database inside the MySQL database, the test database is empty
Two Create model classes
Third, and observe the changes in the Database test table, and found
1 Generating migration files: Generate SQL statements based on model classes, migration files are generated to the migrations directory of the application
2 Perform migration: Execute SQL statement to generate data table
Four into Python manage.py shell-run python shell environment, manipulating model classes and objects, observing table changes
Adding object properties to a table by using an object-oriented approach to add data
In order to look at the object-oriented process more intuitively, the new Str method is added to the model class
Modify the table with object-oriented methods, modify object properties,
By object-oriented methods, deleting an object and then deleting the object in the table corresponds to a single piece of data
The relationship between Django model classes, migrations, and database tables