Home > Article > Backend Development > Detailed introduction to database settings in django (code example)
This article brings you a detailed introduction (code example) about database settings in Django. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
First define the table name and fields of the database
Start the mysql database bash mysql.server start
Install pymysql pip install pymysql
PyMySQL is a library used to connect to the MySQL server in the Python3.x version, and mysqldb is used in Python2.
Add the following code to the _init_.py file:
pymysql.install_as_MySQLdb()
mysql -u root -p Log in root
show databases Show database
create database mysite Create database
2) Modify the DATABASES option of the settings.py file to configure the database
3) Set what you want to use database. For example, mysql
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysite', 'USER': 'root', 'PASSWORD': '12345678', 'HOST': 'localhost', 'PORT': '3306', } }
Use the command python manage.py startapp myApp, and then generate the myApp directory and related files.
admin.py Site configuration
models.py Define model
views.py Define view
INSTALLED_APPS = [
'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myApp',]
2) Define the model, one database table corresponds to one model.
Add something similar to the following in models.py:
class Grades(models.Model):
gname = models.CharField(max_length=20) gdate = models.DateTimeField() ggirlnum = models.IntegerField() gboynum = models.IntegerField() isDelete = models.BooleanField(default=False)ps: There is no need to define the primary key, it will be automatically generated later. 3) Survive the database table in the database
python manage.py makemigrations
python manage.py migrate
The above is the detailed content of Detailed introduction to database settings in django (code example). For more information, please follow other related articles on the PHP Chinese website!