赞
踩
新建一个项目 mysite, 再新建一个 app,名称为blog
- django-admin.py startproject mysite
- cd mysite
- python manage.py startapp blog
修改blog中models.py文件
- from django.db import models
-
- class Blog(models.Model):
- title = models.CharField(max_length=100)
- content = models.TextField()
-
- def __str__(self):
- return self.title
将blog加入到settings的INSTALLED_APPS中
1. 生成迁移文件并创建表
- python manage.py makemigrations blog
- python manage.py migrate blog
2. 向表中添加数据
- python manage.py shell
-
- from blog.models import Blog
- Blog.objects.create(title="your title", content="your content")
or
- blog = Blog(title="title 1", content="content 1")
- blog.save()
3. 批量导入数据
比如有如下内容的blog.txt:
- title 1****content 1
- title 2****content 2
- title 3****content 3
- title 4****content 4
- title 5****content 5
- title 6****content 6
将以上数据导入新建的表中,可用如下操作:
- from blog.models import Blog
-
- with open("blog.txt") as f:
- for line in f:
- title,content = line.split('****')
- Blog.objects.create(title=title, content=content)
or
- from blog.models import Blog
-
- Blog_list = []
- with open('blog.txt') as f:
- Blog_list = [Blog(title=line.split('****')[0], content=line.split('****')[1] for line in f]
- Blog.objects.bulk_create(Blog_list)
Blog.objects.create() 每保存一次就会去执行一条SQL, 而bulk_create()是保存多条数据执行一条SQL,速度更快~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。