Create a new project mysite, and then create a new app named blog
django-admin.py startproject mysite cd mysite python manage.py startapp blog
Modify the models.py file in the blog
from django.db import models class Blog(models.Model): title = models.CharField(max_length=100) content = models.TextField() def __str__(self): return self.title
Add blog to INSTALLED_APPS of settings
1. Generate migration files and create tables
python manage.py makemigrations blog python manage.py migrate blog
2. Add data to the table
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. Batch import data
For example, blog.txt with the following content:
title 1****content 1 title 2****content 2 title 3****content 3 title 4****content 4 title 5****content 5 title 6****content 6
To import the above data into the newly created table, use the following operations:
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() executes an SQL every time it is saved, while bulk_create() saves multiple pieces of data and executes an SQL, which is faster~