安装驱动
pip install mysqlclient
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'root',
'PASSWORD': 'hirain123',
'HOST': 'localhost',
'PORT': '3306',
'OPTION'; {
'init_command': 'SET sql_model="STRICT_TRANS_TABLES"',
}
}
}
from django.db import models
class User(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
level = models.IntegerField(default=1)
createTime = models.DateTimeField(null=True)
class Meta:
db_table = 'User'
如果熟练使用Mysql或SQLyog这类可视化工具操作数据库的话,这步可以省略
from django.contrib import admin
from . import models
admin.site.register(models.User)
生成迁移文件
python manage.py makemigrations
同步到数据库中
python manage.py migrate
使用models必须创建模型
查所有
list = User.objects.all()
isdict = serializers.serialize('json', list)
return HttpResponse(isdict, content_type="application/json")
# filter相当于SQL中的WHERE,可设置条件过滤结果
response2 = Test.objects.filter(id=1)
# 获取单个对象
response3 = Test.objects.get(id=1)
# 限制返回的数据 相当于 SQL 中的 OFFSET 0 LIMIT 2;
Test.objects.order_by('name')[0:2]
#数据排序
Test.objects.order_by("id")
# 上面的方法可以连锁使用
Test.objects.filter(name="runoob").order_by("id")
# 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE
test1 = User.objects.get(id=1)
test1.name = 'Google'
test1.save()
# 删除id=1的数据
test1 = User.objects.get(id=1)
test1.delete()
#添加
test1 = User(name='runoob')
test1.save()
连贯
# 往数据库插入数据
UserInfo.objects.create(name=name, password=password, age=age)
# 删除数据
UserInfo.objects.filter(id=1).delete()
UserInfo.objects.all().delete()
UserInfo.objects.filter(id=1).update(name='new_name', age=30)
模型原生查询
#dade = Dade1.objects.all()
dade = Dade1.objects.raw("select * from dade1 limit 1")
isdict = serializers.serialize('json', dade)
原生sql
导入:from django.db import connection
cursor = connection.cursor()
#插入
cursor.execute("insert into hello_author(name) values('xiaol')")
#更新
cursor.execute("update hello_author set name='xiaol' where id=1")
#删除
cursor.execute("delete from hello_author where name='xiaol'")
#查询
cursor.execute("select * from hello_author")
#返回一行
raw = cursor.fetchone()
print(raw)
# #返回所有
# cursor.fetchall()
自动生成models
python manage.py inspectdb > myFirstWeb/models.py
生成迁移文件
python manage.py makemigrations
同步到数据库中,已有表,生成有加入admin中
python manage.py migrate
dade = Dade1.objects.all()
isdict = serializers.serialize('json', dade)
return HttpResponse(isdict, content_type="application/json")