本帖最后由 xiaoye 于 2017-4-15 13:11 编辑
说明:本文不是0基础文,需要有些python和Django基础 原本来源i春秋,未经允许不得转载 话说,,是不是没多少人学Django啊,,https://bbs.ichunqiu.com/thread-21706-1-1.html 都没人回,贼尴尬。。看的人不多我以后就不更Django了,写点别的 这次分享一个Django小脚本,批量导入数据的,不需要一条一条.objects.get_or_create() 我的models.py里是这样的,新建了一个类: [Python] 纯文本查看 复制代码 ?
| 1 2 3 4 5 6 | class users(models.Model): name = models.CharField(max_length=30) age = models.IntegerField() def __unicode__(self): return self.name |
为了演示,当然要先生成一些数据,人懒不想手动敲数据,写个脚本自己生成数据好了 [Python] 纯文本查看 复制代码 ?
| 01 02 03 04 05 06 07 08 09 10 11 12 | #coding: utf-8 global n n = 1 def main(): demo = 'qwertyuiopasdfghjklzxcvbnm' li = list(demo) for i in li: global n print i + '**' + str(n) n = n + 1 if __name__ == '__main__': main() |
数据生成好了
写个脚本,利用.objects.bulk_create()批量导入数据 [Python] 纯文本查看 复制代码 ?
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 | #coding: utf-8 import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") import django django.setup() def main(): from blog.models import users li = [] with open('db.txt','r') as f: for db in f.readlines(): db = db.strip('\n') dbl = db.split('**') li.append(users(name=dbl[0],age=int(dbl[1]))) users.objects.bulk_create(li) if __name__ == '__main__': main() print 'data import ok' |
运行之后python manage.py shell,然后查看数据是否已经导入 ok,应该是导入好了,但是这样看起来很费劲,我们来写个可视化的html来显示数据: 首先在views.py,视图里面写上一个渲染html页面的函数: [Python] 纯文本查看 复制代码 ?
| 1 2 3 | def user_show(request): user_list = blog_models.users.objects.all() return render(request, 'blog/user_show.html', {'user_list':user_list}) |
html页面: [HTML] 纯文本查看 复制代码 ?
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <html> <head> <title>django sqlite3 show</title> </head> <body> <div> <table border="1"> <thead> <tr> <th> username </th> <th> age </th> </tr> </thead> <tbody> {% for i in user_list %} <tr> <td> {{i.name}} </td> <td> {{i.age}} </td> </tr> {% endfor %} </tbody> </table> </div> </body> </html> |
urls.py: [Python] 纯文本查看 复制代码 ?
| 1 | url(r'^userlist_show/$', blog_views.user_show) |
效果就是:
看左侧,表格里已经出现所有数据了,包括我们刚刚导入的数据 |
转载于:https://my.oschina.net/ichunqiu/blog/888341