Django creates tables using models
The Django model is related to the database, and the code related to the database is generally written in models.py. Django supports sqlite3, MySQL, PostgreSQL and other databases, which only needs to be configured in settings.py, and there is no need to change the code in models.py. Rich API is very convenient to use.
Create a tabl
Let's open the mysite/models.py file and modify the code as follows:
# coding:utf8from django.db import modelsclass Userlist (models.Model): username = models.CharField (max_length=50) password = models.CharField (max_length=50)
We have created a new Userlist class, which inherits from models.Model, and has a user name and password in the user list. A Field is used here, and more Field types can be found in the link at the end of the tutorial.
Synchronize database
Python manage.py makemigrationsMigrations for 'learn': 0006_userlist.py:-Create model UserListpython manage.py migrateOperations to perform: Synchronize unmigrated apps: staticfiles, messages Apply all migrations: admin, contenttypes, sessions, auth, learnSynchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL...Running migrations: Rendering model states... DONE Applying learn.0006_userlist... OK
Registration form
Open the mystie/admin.py file and modify the code:
From django.contrib import adminfrom learn.models import * # Register your models here.class UserlistAdmin (admin.ModelAdmin): list_display = ['username','password'] admin.site.register (Userlist,UserlistAdmin)
Access background management
Http://127.0.0.1:8000/admin
How do I delete a table?
1. Delete the corresponding class in mysite/models.py
2. Delete the classes registered in mysite/admin.py
3. Database synchronization
Python manage.py makemigrationspython manage.py migrate
4. Access backend management
You can see that the Userlist table is gone.