1. In django, a class corresponds to a table.
Define the table name:
The DATABASES in setting.py sets the database selection 'ENGINE': 'django.db.backends.mysql', name 'NAME':'', Account 'USER':'', password 'PASSWORD':'', The server IP of the database 'HOST':'mysql.. . . .com', Port 'PORT': '7150', the port number is also a string, the default is 3306, the remote will change it for security. Models are created with classes, one class and one table.
2. All database operations are created in the models.py file under the APP. Models are created in the model.py file:
from _future_ import unicode-literals from django.db import models class PosModel(models.Model): models.Model inherits the Model class in models. The Model class is a parent class, and there is no base class. username = models.CharField(max_length=16,null=False) defines a field type, the name is username, the maximum length is 16, and it cannot be empty. password = models.CharField(max_length=32,null=False) age = models.IntegerField(null=True) Also creates a field named id by default
3. Migrate to the database through the command:
python manage.py makemigrations create mapping files python manage.py migrate to pass the mapping file into the database
4. Insert data into the database
Import the model in the views.py file:
from django.http inport HttpResponse from models import PosModel def index(request): posModel = PosModel(username='',password='',age='') posModel.save() writes to the database posModel = PosModel.object.get(id=1) Get data from database. username = posModel.username password = posModel.password age = posModel.age return HttpResponse('%s\n%s\n%s' %(username,password,age))
Add a new APP model to the database:
Add a command like this in the admin.py file:
from django.contrib import admin import background admin from django.contrib module from .models import PosModel Import the model PosModel from the models.py file in the current directory admin.site.register(PosModel) background.partition.register(PosModel model)