Before reading this chapter, you need to first read (#) for basic configuration and to understand common problem solutions.
Next, let's recreate a project app01 (ignore the following operations if you have already created it):
django-admin.py startproject app01
Next, find the INSTALLED_APPS item in settings.py, as follows:
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', # Add this item)
Next, tell Django to use the pymysql module to connect to the mysql database:
## Instance
# Introduce module and configure in __init__.py under the same level as settings.py
import pymysql
pymysql.install_as_MySQLdb()
### Create Model
Add the following class in models.py of the project:
## app01/models.py
class Book(models.Model):
id = models.AutoField(primary_key=True)# id will be created automatically, you can also write it manually
title = models.CharField(max_length=32)# Book title
price = models.DecimalField(max_digits=5, decimal_places=2)# Book price
publish = models.CharField(max_length=32)# Publisher name
pub_date = models.DateField()# Publication date
Then execute the following commands in the command line:
$ python3 manage.py migrate # Create table structure
$ python3 manage.py makemigrations app01 # Let Django know we have some changes in our model
$ python3 manage.py migrate app01 # Create table structure
### Common Error Messages
If executing the above commands results in the following error:
!(#)
The reason is that MySQLclient currently only supports up to Python3.4, so if you are using a higher version of python, you need to modify as follows:
Find the base.py file in the path ...site-packagesDjango-2.0-py3.6.eggdjangodbbackendsmysql through the file path in the error message, and comment out these two lines of code (the code is at the beginning of the file):
if version < (1, 3, 13): raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database. __version__ )
!(#)
Generally, clicking on the code file path information in the error will automatically jump to the line number in the error file. At this time, we comment out the code at the error line.
At this time, the database tutorial will create a table named app01_book.
Next, we add views.py and models.py files in the app01 project. The app01 project directory structure:
app01 |-- app01 | |-- __init__.py | |-- __pycache__ | |-- asgi.py | |-- migrations | |-- models.py | |-- settings.py | |-- urls.py | |-- views.py | `-- wsgi.py
### Database Addition
Rule configuration:
## app01/urls.py: File code:
from django.contrib import admin from django.urls import path from . import views urlpatterns = [path('add_book/', views.add_book), ]
**Method 1:** Model class instantiated object
Need to import models.py file from the app directory:
from app directory import models
And after instantiating the object, you must execute object.save() to successfully add to the database.
## app01/views.py: File code:
from django.shortcuts import render,HttpResponse from app01 import models def add_book(request): book = models.Book(title="",price=300,publish="Tutorial Publishing House",pub_date="2008-8-8")book.save()return HttpResponse("
Data added successfully!
")
!(#)
**Method 2:** Use the create method provided by ORM's objects (recommended)
## app01/views.py: File code:
from django.shortcuts import render,HttpResponse from app01 import models def add_book(request): books = models.Book.objects.create(title="Palm of God",price=200,publish="Kungfu Publishing House",pub_date="2010-10-10")print(books, type(books))return HttpResponse("
Data added successfully!
")
!(#)
### Query
Use the **all()** method to query all content.
It returns QuerySet type data, similar to list, which contains objects of the model class one by one. You can use index subscript to get the model class object.
## app01/views.py: File code:
from django.shortcuts import render,HttpResponse from app01 import models def add_book(request): books = models.Book.objects.all()print(books,type(books))return HttpResponse("
Query successful!
")
!(#)
!(