Django如何批量创建Model

所属分类: 脚本专栏 / python 阅读数: 1978
收藏 0 赞 0 分享

1.前言:

将测试数据全部敲入数据库非常繁琐,而且如果与合作伙伴一起开发,部署,那么他们肯定也不想把时间花在一个一个录入数据的繁琐过程中,这时候,创建一个批量录入数据的脚本(population script)就非常有必要。

2.代码:

假设在models.py中定义的数据为下面:

from django.db import models
 
# Create your models here.
class Category(models.Model):
  name=models.CharField(max_length=128,unique=True)
  class Meta:
    verbose_name_plural="Categories"
  def __str__(self):
    return self.name
 
class Page(models.Model):
  category=models.ForeignKey(Category,on_delete=models.CASCADE)
  title=models.CharField(max_length=128)
  url=models.URLField()
  views=models.IntegerField(default=0)
  def __str__(self):
    return self.title

populate.py如下(仅供参考):

import os
# In your live server environment, you'll need to tell your WSGI application what settings
# file to use. Do that with os.environ:
#reference source:https://docs.djangoproject.com/en/3.1/topics/settings/
os.environ.setdefault('DJANGO_SETTINGS_MODULE','tango_with_django_project.settings')
 
import django
django.setup()
from rango.models import Category,Page
#If you're using components of Django “standalone” – for example, writing a Python script
# which loads some Django templates and renders them, or uses the ORM to fetch some data –
# there's one more step you'll need in addition to configuring settings.
# After you've either set DJANGO_SETTINGS_MODULE or called configure(), you'll need to call
# django.setup() to load your settings and populate Django's application registry.
# reference source:https://docs.djangoproject.com/en/3.1/topics/settings/
def populate():
  python_pages=[
    {"title":"official",
    "url":"http://docs.python.org"},
    {"title":"How to think like a computer scientis",
    "url":"http://ww.greenteapress.com/thinkpy"},
    {"title":"learn python in 10 minites",
    "url":"http://www.korokithakis.net/tutorials/python"}
  ]
 
  django_pages=[
    {"title":"Official Django tutorial",
    "url":"https://docs.jangoproject.com/en/1.9/intro"},
    {"title":"Django Rocks",
    "url":"http://www.djangorocks.com"
    },
    {"title":"HOw to tango with django",
    "url":"http://www.tangowithdjango.com"}
  ]
 
  other_pages=[
    {"title":"Bottle",
    "url":"http://bottlepy.org"},
    {"title":"Flask",
    "url":"http://flask.pocoo.org"},
    {"title":"Bold test",
    "url":"http://boldtest.org"}
  ]
  cats={"Python":{"pages":python_pages},
  "Django":{"pages":django_pages},
  "Other Frameworks":{"pages":other_pages}}
 
  def add_page(cat,title,url,views=0):
    p=Page.objects.get_or_create(category=cat,title=title,url=url,views=views)[0]
    # p.url=url
    # p.views=views
    p.save()
    return p
  def add_cat(name):
    c=Category.objects.get_or_create(name=name)[0]
    c.save()
    return c
  for cat,cat_data in cats.items():
    c=add_cat(cat)
    for p in cat_data['pages']:
      add_page(c,p["title"],p['url'])
  for c in Category.objects.all():
    for p in Page.objects.filter(category=c):
      print("-{0}-{1}".format(str(c),str(p)))
 
if __name__=="__main__":
  print("starting rango population script")
  populate()

 3.代码要点

(1)在独立运行django的代码时,而不是通过 python manage.py runserver的方式运行时,必须使用django.setup()来引入Django项目的设置,而在引入设置之前还要指明 环境变量DJANGO_SETTINGS_MODULE用的是本项目的settings。

设置环境变量在python中常用os.environ,它返回一个字典类型,里面包含了所有环境变量的键值对,所以在这里使用字典的内置方法setdefault,将环境变量

'DJANGO_SETTINGS_MODULE' 设置为'tango_with_django_project.settings'(本项目的settings.py)。<br>参考:<a href="https://docs.djangoproject.com/en/3.1/topics/settings/#envvar-DJANGO_SETTINGS_MODULE" rel="external nofollow" >https://docs.djangoproject.com/en/3.1/topics/settings/#envvar-DJANGO_SETTINGS_MODULE</a>

(2)get_or_create方法:(官方文档定义https://docs.djangoproject.com/en/3.1/ref/models/querysets/#get-or-create如下)

get_or_create(defaults=None, **kwargs)
A convenience method for looking up an object with the given kwargs (may be empty if your model has defaults for all fields),<br> creating one if necessary.
Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new <br>object was created.
This is meant to prevent duplicate objects from being created when requests are made in parallel, and as a shortcut to boilerplatish code. <br>

 在这里,需要注意的是,如果在创建model instance时,仅在model有默认值的情况下可以不输入任何kwargs,否则必须至少输入一个值(field,如这里page的category,或者Category的name),然后该方法会带着这个值先去找有没有该值下的model instance,如果没有则创建一个新的,返回(object,created),这里object 是新创建的对象的reference,created为True.

4.运行查看

运行python populate.py:

然后登陆admin页面查看:

可以看到,数据全部被读入数据库。

以上就是Django如何批量创建Model的详细内容,更多关于Django批量创建Model的资料请关注脚本之家其它相关文章!

更多精彩内容其他人还在看

Python简单操作sqlite3的方法示例

这篇文章主要介绍了Python简单操作sqlite3的方法,结合实例形式分析了Python针对sqlite3数据库的读取、创建、增删改查等基本操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python实现遍历目录的方法【测试可用】

这篇文章主要介绍了Python实现遍历目录的方法,涉及Python针对目录与文件的遍历、判断、读取相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

python条件变量之生产者与消费者操作实例分析

这篇文章主要介绍了python条件变量之生产者与消费者操作,结合具体实例形式分析了Python条件变量的概念、原理、及线程操作的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

利用pyinstaller或virtualenv将python程序打包详解

这篇文章主要给大家介绍了利用pyinstaller将python程序打包的相关资料,文中介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
收藏 0 赞 0 分享

Python多线程经典问题之乘客做公交车算法实例

这篇文章主要介绍了Python多线程经典问题之乘客做公交车算法,简单描述了乘客坐公交车问题并结合实例形式分析了Python多线程实现乘客坐公交车算法的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python编程实现删除VC临时文件及Debug目录的方法

这篇文章主要介绍了Python编程实现删除VC临时文件及Debug目录的方法,涉及Python针对文件与目录的遍历、删除等相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

python3中dict(字典)的使用方法示例

这篇文章主要介绍了python3中dict(字典)的使用方法,文中给出了详细的功能列举,对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
收藏 0 赞 0 分享

Python中.py文件打包成exe可执行文件详解

这篇文章主要给大家介绍了在Python中.py文件打包成exe可执行文件的相关资料,文中介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
收藏 0 赞 0 分享

Python编程之event对象的用法实例分析

这篇文章主要介绍了Python编程之event对象的用法,结合实例形式分析了event对象在线程通信中的作用与使用方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Python爬取网页中的图片(搜狗图片)详解

没想到python是如此强大,令人着迷,以前看见图片总是一张一张复制粘贴,现在好了,学会python就可以用程序将一张张图片,保存下来。下面这篇文章主要给大家介绍了利用Python3.6爬取搜狗图片网页中图片的相关资料,需要的朋友可以参考下。
收藏 0 赞 0 分享
查看更多