1.将mysql中的表同步到models中
在项目目录下执行: python manage.py inspectdb #用来查看数据库以及对应表结构 python manage.py inspectdb > models.py #直接同步也没有问题
2.views.py 中 从models引入表对应的类
from wordcloud.models import Sc20170811 names=Sc20170811.objects.all()[:10] 取前十个 # print (str(Sc20170811.objects.all()[:10].query)) 会在启动服务器的cmd处打印当前的查询语句
得到的names 可以和其它变量一样通过context 传递到html中
对应完整代码:
views.py from django.http import HttpResponse from django.template import loader,Context from wordcloud.models import Sc20170811 # Create your views here. def index(requests): template = loader.get_template('wordcloud.html') names=Sc20170811.objects.all()[:10] print (str(Sc20170811.objects.all()[:10].query)) print(type(names)) context = { "value":"我是标题",'names':names} return HttpResponse(template.render(context))
3 html文件中从以变量形式取值
{% for name in names %}
{{name.title}}
{% endfor %}
4.一些细节内容:
查询语句: print (str(Sc20170811.objects.all()[:10].query))对应下面 SELECT `sc_20170811`.`id`, `sc_20170811`.`leading_title`, `sc_20170811`.`title`, `sc_20170811`.`subtitle`, `sc_20170811`.`link`, `sc_20170811`.`writeTime`, `sc_20170811`.`source`, `sc_20170811`.`section`, `sc_20170811`.`author`, `sc_20170811`.`news`, `sc_20170811`.`updated` FROM `sc_20170811` LIMIT 10
报错解决过程:
中间有报错说 unkonwn column sc_20170811.id,后来自己手动在数据库增加一个id字段,运行python manage.py inspectdb > models.py从数据库同步到models之后,数据被取出来了一次,过后又报错。说id必须为主键,但是我刚插入的字段不可能为主键的。(记录太多)于是又删除了id字段,从数据库同步到models,终于恢复正常。
报错信息:
wordcloud.Sc20170811: (models.E004) ‘id’ can only be used as a field
name if the field also sets ‘primary_key=True’.
unkonwn column sc_20170811.`id
5.参考资料:
Django QuerySet API
jango QuerySet 进阶
Django读取Mysql数据并显 示在前端(版本不一致,有很大区别)
官方文档:Integrating Django with a legacy database?