配置
settings.py
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
'NAME':'307_django_db',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
先创建指定名称的数据库databases
create database self_django_db DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
models.py
from django.db import models
class Comment_info(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
date = models.CharField(max_length=255, blank=True, null=True)
content = models.CharField(max_length=5000, blank=True, null=True)
# Create your models here.
终端命令:
python manage.py makemigrations
python manage.py migrate
函数
views.py
from app_307.models import Comment_info
def get(request):
# data_list = [
# {"comment":"今天天气很好","date":"11.18","name":"左xx"},
# {"comment":"今天很开心","date":"3.21","name":"刘xx"},
# {"comment": "乐", "date": "3.3", "name": "靖xx"}
# ]
# data_list = json.dumps(list(Comment_info.objects.all().values('name','date','content')))
data_list = []
for item in Comment_info.objects.all():
data_list.append({
'name': item.name,
'content': item.content,
'date':item.date,
})
request_data = {"code":200,"message":"请求成功"}
request_data["data"] = data_list
return JsonResponse(request_data,safe=False)
注意将查询结果转化成Json的形式,尝试了很多方法,貌似就这一种成功了。应该还有其它的方法。