setting.py
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
#數(shù)據(jù)庫名字
'NAME': 'study',
'USER': 'root',
'PASSWORD': 'centos',
'HOST': '127.0.0.1',
'PORT': '3306',
'OPTIONS': {
'autocommit': True,
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
安裝相關(guān)模塊
python3 不在支持MySQLdb
安裝pymsqlpip3 install pymysl
#去項(xiàng)目下修改__init__.py,使其默認(rèn)數(shù)據(jù)庫模塊為pymysql
import pymysql
pymysql.install_as_MySQLdb()
項(xiàng)目下執(zhí)行
python manage.py makemigrations
python manage.py migrate
操縱models.py
數(shù)據(jù)庫相關(guān)一般都寫在這個(gè)模塊下 前提肛循,應(yīng)用要加到setting中
from django.db import models
# Create your models here.
#新建了一個(gè)Student類层释,繼承自models.Model
class Student(models.Model):
name = models.CharField(max_length=128)
age = models.IntegerField(max_length=3
#上面代碼其實(shí)就相當(dāng)于原生sql
CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"name" varchar(30) NOT NULL,
"age" int() NOT NULL
);
#然后進(jìn)行同步
python manage.py makemigrations
python manage.py migrate
#生成一個(gè)
項(xiàng)目名稱+下劃線+小寫類名的表
比如項(xiàng)目叫study_1,那表名就叫study_1_student
#插入數(shù)據(jù)
class Student(models.Model):
Student.objects.create(name='lizili',age=18)
Student.objects.create(name='vic',age=22)
Student.objects.create(name='zhang',age=12)
#返回?cái)?shù)據(jù)
def __str__(self): #固定格式
return u'name: %s , age:%s' % (self.name,self.age)
#需要數(shù)據(jù)的頁面
#導(dǎo)入
from study_1.models import Student
#查詢怎静,展示
def test(request):
student_list = Student.objects.all()
student_str = map(str,student_list)
return HttpResponse(student_str)