环境:
python 3.8
django 3.0
mysql 8.0.25-0ubuntu0.20.04.1
pip install pymysql
CREATE DATABASE django_voco;
import pymysql
pymysql.install_as_MySQLdb()
DATABASES = {
'default': {
# 配置使用mysql
'ENGINE': 'django.db.backends.mysql', # 数据库产品
'HOST': "localhost", # 数据库ip
'PORT': 3306, # 数据库端口
'USER': "root", # 用户名
'PASSWORD': "passwd", # 密码
'NAME': "django_voco", # 数据库名
}
}
class accounts(models.Model):
id = models.CharField('id', primary_key=True, max_length=10)
mail = models.CharField('mail', max_length=50)
passwd = models.CharField('passwd', max_length=50)
// 创建迁移文件
python3 manage.py makemigrations
// 现步迁移文件到数据库
python3 manage.py migrate
重新运行程序后可看到已经在数据库中创建了一张表:
from voco_app.models import user_info
# Create your views here.
@csrf_exempt
def index(request):
print("run index!")
if request.method == "POST":
req = json.loads(request.body)
info = user_info()
info.uuid = req["uuid"]
info.mail = req["mail"]
info.passwd = req["passwd"]
info.save()
print (req)
# return JsonResponse({"status":"200","msg":"ojbk"})
return HttpResponse("ok")
@csrf_exempt
def get_user_info(request):
print("run get_user_info!")
if request.method == "POST":
result = user_info.objects.filter(user_id=1)
arr = []
for i in result:
content = {'user_id': i.user_id, 'mail': i.mail, 'passwd': i.passwd}
arr.append(content)
return HttpResponse(arr)
7.在django后台管理数据
admin.site.register(user_info)
就可以在后台看到数据库的内容了,可以做些简单的增删改查操作: