models.py:
from django.db import models
# Create your models here.
class Blog(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
新建一个.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
title 7****content 7
title 8****content 8
title 9****content 9
第一种方法:
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "loaddata.settings")
django.setup()
def main():
from blog.models import Blog
f = open('data.txt')
for line in f:
title, content = line.split('****')
Blog.objects.create(title=title, content=content)
f.close()
if __name__ == '__main__':
main()
解决导入数据重复:
Blog.objects.get_or_create(title=title,content=content) #换成这行代码,有则返回False,没有则创建并返回True
第二种方法:bulk_create()
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "loaddata.settings")
def main():
from blog.models import Blog
f = open('data.txt')
BlogList = []
for line in f:
title,content = line.split('****')
blog = Blog(title=title,content=content)
BlogList.append(blog)
f.close()
Blog.objects.bulk_create(BlogList) #bulk_create()执行一条SQL语句可以保存多条数据
if __name__ == "__main__":
main()