64. django model layer (model)-basic for table creation, query, and deletion, djangomodel
The most important part of a project is definitely data, that is, the database. This article will introduce you to django's use of the model layer model, model is used to add, delete, modify, and query databases without using SQL statements. This article only guides you through simple table creation, query, and deletion. Because of the importance of model, the subsequent articles will focus on ORM.
I. ORM
Ing:
Table name <-------> Class Name
Field <-------> attribute
Table Record <-------> class instance object
2. Create a table (create a model)
1. The code for creating a table is written in the models file of the project.
1) For example, we create a book table and create it as follows:
From django. db import models # Create your models here. class Book (models. model): nid = models. autoField (primary_key = True) # AutoField ordered integer title = models. charField (max_length = 32) # CharField character author = models. charField (max_length = 32) publishDate = models. dateField () # DateField date type price = models. decimalField (max_digits = 5, decimal_places = 2) # FloatField can also be used in DecimalField
The class name is the table name, and the attribute is the field. Only the models. Model provided by django for conversion can convert the classes we write into databases.
After defining the models, you need to tell Django to use these models. All you need to do is modify the configuration file.
2) common field parameters
(1) If null is True, Django uses NULL to store null values in the database. The default value is False. (1) If blank is True, this field is not allowed. The default value is False. Note that this is different from null. Null is purely a database category, while blank is a data validation category. If the blank of a field is True, the Form validation will allow this field to be null. This field is required if blank is set to False. (2) default value of the default field. It can be a value or callable object. If you call it, it is called every time a new object is created. (3) If primary_key is True, this field is the primary key of the model. If you do not specify primary_key = True for any field, Django will automatically add an IntegerField as the primary key, so unless you want to override the default primary key behavior, otherwise, you do not need to set primary_key = True for any field. (4) If the value of unique is set to True, the value of this data field must be unique in the whole table. (5) choices is a iteratable object composed of binary groups (for example, list or tuples), used to provide selection items for fields. If choices is set, the default form will be a selection box instead of a standard text box, and the option in this selection box is the option in choices. This is an example of the choices list: YEAR_IN_SCHOOL_CHOICES = ('F', 'freshman '), ('so', 'sophomor'), ('jr ', 'junior'), ('sr', 'Senior '), ('gr', 'graduate'),) the first element in each tuples is the value stored in the database; the second element is used as the display content on the management interface or ModelChoiceField. In a given model class instance, if you want to get the display value of a choices field, call the get_FOO_display method (FOO here is the name of the choices field ). Example: from django. db import modelsclass Person (models. model): SHIRT_SIZES = ('s ', 'small'), ('M', 'medium'), ('l', 'large '),) name = models. charField (max_length = 60) shirt_size = models. charField (max_length = 1, choices = SHIRT_SIZES) >>> p = Person (name = "Fred Flintstone", shirt_size = "L") >>> p. save () >>> p. shirt_size 'l'> p. get_shirt_size_display () 'large'
View Code
2. modify the configuration file setting
1) django uses the sqlite3 database by default. We use the mysql database, so we need to modify the configuration.
Original configuration (comment out these configurations)
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}
Reconfiguration
DATABASES = {'default': {'Engine ': 'django. db. backends. mysql ', 'name': 'blog', # Your database NAME database needs to be created in advance 'user': 'root', # Your database username 'Password ': '', # Your Database Password 'host':'', # Your Database HOST, default localhost 'Port': '123', # Your Database PORT }}
3. Create a table command
1) synchronously change database tables or fields
Earlier versions: python manage. py syncdb Django 1.7.1 and later versions require the following command: python manage. py makemigrationspython manage. py migrate
2) After running python manage. py makemigrations, a file will be automatically generated in the migrations folder under our application, which will further convert the class we wrote:
# -*- coding: utf-8 -*-# Generated by Django 1.11.6 on 2017-10-25 03:30from __future__ import unicode_literalsfrom django.db import migrations, modelsclass Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('nid', models.AutoField(primary_key=True, serialize=False)), ('title', models.CharField(max_length=32)), ('author', models.CharField(max_length=32)), ('publishDate', models.DateField()), ('price', models.DecimalField(decimal_places=2, max_digits=5)), ], ), ]
3) after running python manage. py migrate, the table will be inserted into our database.
4) Note:
If python version 3.x is used to run the above two statements, an error is reported.
No module named "MySQLdb"
In 3.x, the database uses the pymysql module, so we need to tell django to use pymysql.
Add code to the _ init _. py file of the application.
import pymysqlpymysql.install_as_MySQLdb()
View in the database after running:
We will find that django has created many tables for us. The Book table we created will be automatically renamed as application name_book, which avoids having the same table in different applications, other tables will be introduced one by one later.
Iii. View tables
1. retrieve the data in the view function view.
From app01 import models # app01 is the application name def index (request): # retrieve all the book objects from the database bookList = models. book. objects. all () # [bookObj1,...] return render (request, "index.html", {"bookList": bookList })
Query Problems
<1> all (): Query all results <2> filter (): query the objects matching the filtering conditions.
2. Receive In template
{% for book_obj in bookList %} <tr> <td>{{ book_obj.nid }}</td> <td>{{ book_obj.title }}</td> <td>{{ book_obj.author }}</td> <td>{{ book_obj.publishDate|date:"Y-m-d" }}</td> <td>{{ book_obj.price }}</td> </tr>{% endfor %}
Iv. Delete
The delete method is delete (). It immediately deletes the object while running without returning any value.
For example, we add a delete button to the table to delete each record of the database after clicking the button.
1. template
{% For book_obj in bookList %} <tr> <td >{{ book_obj.nid }}</td> <td >{{ book_obj.title }</td> <td> {{ book_obj.author }}</td> <td >{{ book_obj.publishDate | date: "Y-m-d" }}</td> <td >{{ book_obj.price }}</td> <a href = "/del/{book_obj.nid}} "> <button class =" btn-danger "> Delete </button> </a> </td> </tr >{% endfor %}
2. url Distribution
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index), url(r'^del/(\d+)', views.delBook),]
3. view function view Deletion
def delBook(request,id): models.Book.objects.filter(nid=id).delete() return redirect("/index/")