Django 数据导入:
备注:你可能会问数据从哪儿来,比如你用python从以前的blog上获取过来的,
想导入现在的博客,或者别人整理好的数据,或者你自己整理的excel表
我们新建一个项目 mysite, 再新建一个 app,名称为blog
django-admin.py startproject mysite
cd mysite
python manage.py startapp blog
把 blog 中的 models.py 更改为以下内容
node2:/app/mysite/blog#cat models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __unicode__(self):
return self.title
不要忘了把blog加入到settings.py中的INSTALLED_APPS 中。
# Application definition
INSTALLED_APPS = (
...
# 添加上 blog 这个 app
'blog',
)
一,同步数据库,创建相应的表
node2:/app/mysite#python manage.py makemigrations^C
node2:/app/mysite#set -o vi
node2:/app/mysite#python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
Applying blog.0001_initial... OK
二,输入 python manage.py shell
进入该项目的django环境的终端(windows如何进入对应目录?)
先说如何用命令新增一篇文章:
$ python manage.py shell
>>> from blog.models import Blog
>>> Blog.objects.create(title="The first blog of my site", content="I am writing my blog on Terminal")
node2:/app/mysite# python manage.py shell
Python 2.7.3 (default, Mar 30 2017, 20:15:12)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from blog.models import Blog
>>> Blog.objects.create(title="The first blog of my site", content="I am writing my blog on Terminal")
<Blog: The first blog of my site>
>>>
三,批量导入
比如我们要导入一个文本,里面是标题和内容,中间用四个*隔开的,示例(oldblog.txt):
node2:/root#cat aa.txt | awk -F '****' '{print $1,$2}' | while read A B; do sh ./a1.sh $A $B; done
Blog.objects.create(title=title, content=1)
Blog.objects.create(title=title, content=2)
Blog.objects.create(title=title, content=3)
Blog.objects.create(title=title, content=4)
Blog.objects.create(title=title, content=5)
Blog.objects.create(title=title, content=6)
Blog.objects.create(title=title, content=7)
Blog.objects.create(title=title, content=8)
Blog.objects.create(title=title, content=9)
node2:/root#
在终端导入有时候有些不方便,我们在最外面那个mysite目录下写一个脚本,叫
txt2db.py,把 oldblog.txt 也放在mysite下
node2:/app#cat a1.py
import django
print django.VERSION
node2:/app#python a1.py
(1, 11, 0, u'final', 1)
node2:/app/mysite#cat a2.py
#!/usr/bin/env python
#coding:utf-8
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
'''
Django 版本大于等于1.7的时候,需要加上下面两句
import django
django.setup()
否则会抛出错误 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
'''
import django
if django.VERSION >= (1, 7):#自动判断版本
django.setup()
def main():
from blog.models import Blog
f = open('oldblog.txt')
for line in f:
title,content = line.split('****')
Blog.objects.create(title=title,content=content)
f.close()
if __name__ == "__main__":
main()
print('Done!')