Os:mac, django1.9.5, python3.5
Database:mysql
0. Background
Each model in Django corresponds to a table in the database, and the fields in each model correspond to the columns of the database table.
Conveniently, Django can automatically generate these CREATE TABLE, ALTER TABLE, DROP table operations.
Imagine how troublesome it would be if we were to modify the data model in Django every time and also to synchronize the model in the database. Not to mention the mistakes in the details that are apt to happen.
1. Create a model
Let's say we create a simple data model for a shopping mall:
Shopping malls are divided into various areas, such as cosmetics, women's areas, men's areas and so on. Corresponding to the area model, there is the field name name, description description, managers manager.
Next, there are many shops in each region. corresponding to the store model, there is a field shop name name, the foreign key area (area and Store is a one-to-many relationship).
And every shop sells a variety of goods. corresponding to the item model, there is a field product name name, price value, foreign key store (store with Item is a one-to-many relationship).
1 fromDjango.dbImportModels2 fromDjango.contrib.auth.modelsImportUser3 4 5 classArea (models. Model):6Name = models. Charfield (max_length=30)7Description = models. Charfield (max_length=100)8Manager = models. ForeignKey (User, Blank=true, null=True)9 Ten def __str__(self): One returnSelf.name A - - classStore (models. Model): theName = models. Charfield (max_length=30) -Area = models. ForeignKey (area, on_delete=models. CASCADE, related_name= ' stores ') - - def __str__(self): + returnSelf.name - + A classItem (models. Model): atName = models. Charfield (max_length=30) -Price =models. Integerfield () -Store = models. ForeignKey (Store, on_delete=models. CASCADE) - - def __str__(self): - returnSelf.name
1.1 Primary Key
We noted that when we defined the model above, we did not define the primary key primary key. This is because, unless you explicitly specify, Django automatically adds a primary key to your model that has a field name of ID.
id = models. Autofield (Primary_key=true)
Of course, we can also customize the primary key, as long as the field is set Primary_key=true. At this point, Django does not automatically set the ID primary key for our model.
Primary_key=true means Null=false and unique=true. In other words, the primary key is non-null and unique, and it is used to identify this row of data in this table.
In the Django model, the primary key is also read-only.
1.2 Foreign key
When you define a foreign key in a model, after you synchronize the database, Django defaults to the name of the database table by adding "_id" after the external key field names.
The additional parameters commonly used by ForeignKey () are as follows:
Cascade Delete: On_delete=models. CASCADE
Reverse query: If we set realted_name= ' stores ' in the foreign key store field of the store model, you can reverse query to stores at the other end of the relationship, that is, the area end
1.3 __str__ () method
It is a good practice to define the __str__ () method for each model, not just for interaction, but also because Django uses __str__ () to display objects in other places.
Note the __str__ () method must return a string.
2. Generating a model
Each time you modify the model, you need to run the following two commands to synchronize our database:
1 python manage.py makemigrations 2 python manage.py migrate
2.1 Makemigrations
The function of the first command is to generate a migrations file.
In our example, the following output is available in the shell after Makemigrations:
1 for ' Shop ' : 2 0001_initial.py:3 - Create modelarea4 - Create model Store5 -Create model Item
At this time, in our app shop can see a migrations folder, open 0001_initial.py, you can see the corresponding migration statement.
2.2 Migrate
The second command works by applying these migrations to the database.
In our example, the following output is available in the shell after migrate:
1 Operations to perform: 2 Apply All Migrations:silk, sessions, admin, auth, shop, contenttypes3Running migrations: 4 Rendering model states ... done5 applying shop.0001_initial ... Ok
The automatically generated table name is a combination of the app name (shop) and the lowercase name (area, store, item) of the model (with the underscore _ combination). such as the Shop_area table in the model area corresponding to the app shop.
2.3 Description
Each app's migration file is generated under the Migrations folder in the app.
In Django, each time the addition, deletion, or modification of the model and the fields in the model is performed, the corresponding migrations is makemigrations in the execution of the Python manage.py.
It is recommended that you carefully examine the output in the shell after makemigrations, especially when complex changes are made to the model. After the check is finished, execute the migrate.
Of course, if you makemigrations after running the migrate, you can go away and delete the migrations file you just generated.
Everyone deserves a second chance:)
3. Basic operation of the database
3.1 Increase
We'll add a cosmetic area to shopping mall:
1 fromDjango.shortcutsImportHttpResponse2 from. ModelsImport Area3 4 5 defAdd_area (Request):6Area = Area.objects.create (name='Cosmetic', description='an area full of fragrant smells')7 8 returnHttpResponse ('added!')
Where the sixth line of code area = Area.objects.create (name= ' cosmetic ', description= ' aroma-filled region ')
The corresponding MySQL statement is:
Insert into Values (' cosmetic',' fragrance-filled area ');
3.2 Check
Now, let's list all the areas in the shopping mall:
1 fromDjango.shortcutsImportHttpResponse2 from. ModelsImport Area3 4 5 defList_area (Request):6Area =Area.objects.all ()7 Print(area) # in the shell output [<area: ' Cosmetic ';], if not defined __str__ (), will output meaningless [<area:area object>]8 9 returnHttpResponse ('listed!')
Line six Code area = Area.objects.all ()
Equivalent to the MySQL statement:
Select * from Shop_area;
Review: Shop_area the table name (App_model) that is automatically generated for the Django model
3.3 Change
In 3.1, we did not appoint a management person for the cosmetic area. Now, we modify the cosmetic area information and designate Rinka as the management person.
First, we're going to create a Rinka user. Here I will create a superuser named Rinka:
Python manage.py Createsuperuser
Next, we designate the Rinka user who we created as the management of the cosmetic area:
1 fromDjango.shortcutsImportHttpResponse2 from. ModelsImport Area3 fromDjango.contrib.auth.modelsImportUser4 5 6 defUpdate_area (Request):7Rinka = User.objects.get (username='Rinka')8Area = Area.objects.get (id=1)9Area.manager =RinkaTen Area.save () One A returnHttpResponse ('updated!')
Note that the object's Save () method must be called, and modifications to the object instance will not be saved to the database. This is an error-prone place.
The 8th to 10th line of code corresponds to the MySQL statement:
Update set manager_id=1where id=1;
Review: manager_id the column name (foreignkey_id) generated for Django by default for foreign keys
3.4 by deleting
The delete operation is simple and we now delete the row of data with ID 1 in database table Shop_area:
1 fromDjango.shortcutsImportHttpResponse2 from. ModelsImport Area3 4 5 defDelete_area (Request):6Area = Area.objects.get (id=1)7 Area.delete ()8 9 returnHttpResponse ('deleted!')
The MySQL statement corresponding to the 6th to 7th line statement is:
Delete from where id=1;
Summarize
Database basic operations in Django:
1. Synchronizing the database
Python manage.py makemigrations #生成migrations
Python manage.py Migrate #应用migrations
2. Increase
Model.objects.create (**kwargs)
3. Check
Model.objects.all ()
4. Change
m = Model.objects.get (id=1)
M.name = ' new_name '
M.save ()
5. By deleting
m = Model.objects.get (id=1)
M.delete ()
django-database [Basic operations]