Python 批量向Django 导入数据

Python 批量向Django 导入数据-Python 技术分享 Java技术分享 Python 爬虫技术_微信公众号:zeropython—昊天博客
#!/usr/bin/env python
# coding:utf-8

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Movie_site.settings")

'''
Django 版本大于等于1.7的时候,需要加上下面两句
import django
django.setup()
否则会抛出错误 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
'''
import django
django.setup()

"""
class Tag(models.Model):
    tag_name = models.CharField(max_length=30)
    tag_desc = models.CharField(max_length=100)
    tag_slug = models.CharField(max_length=30)
class Director(models.Model):
name = models.CharField(max_length=30)
desc = models.TextField(blank=True)
class Actor(models.Model):
    name = models.CharField(max_length=30)
    desc = models.TextField(blank=True)

    class Dl_links(models.Model):
    links = models.CharField(max_length=200)
    links_name = models.CharField(max_length=30)

class Category(models.Model):
    cate_name = models.CharField(max_length=30)
    cate_desc = models.CharField(max_length=100)
    cate_slug = models.CharField(max_length=30)
"""

def main():
    from movie.models import Tag,Director,Actor,Dl_links,Category
    for i in range(10):
        # Tag.objects.create(tag_name=f"{i}标题",tag_desc=f'{i}描述',tag_slug=f'{i}_url')
        # Director.objects.create(name=f"{i}导演",desc=f'{i}导描述')
        # Actor.objects.create(name=f"{i}演员",desc=f'{i}演员描述')
        # Dl_links.objects.create(links=f"{i}links",links_name=f'{i}links_name')
        Category.objects.create(cate_name=f"分类{i}",cate_desc=f'分类描述{i}',cate_slug=f'{i}_cate')


if __name__ == "__main__":
    main()
    print('Done!')

Model.objects.bulk_create() 更快更方便

#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

def main():
    from blog.models import Blog
    f = open('oldblog.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)

if __name__ == "__main__":
    main()
    print('Done!')
HTTPX 基础教程-新乡seo|网站优化,网站建设_微信公众号:zeropython—昊天博客