Django如何批量创建Model
作者:JohnYang 发布时间:2022-12-29 15:40:39
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页面查看:
可以看到,数据全部被读入数据库。
来源:https://www.cnblogs.com/johnyang/p/13511440.html


猜你喜欢
- 前端的小伙伴们在babel等的加持下,已经可以愉快的使用es6来写代码了。然后对于服务端的nodejs就有点坑爹了,虽然原生支持了es6,但
- 之前在网上看到有人提问,如何在页面上同步显示服务器的时间,其实实现方法有几种,可能 一般人立马就想到可以使用Ajax每隔一秒去请求服务器,然
- remove()方法从列表中删除第一个obj。语法以下是remove()方法的语法:list.remove(obj)参数&nbs
- Oracle过程和函数相信大家都比较了解,下面就为您详细介绍Oracle过程和函数二者之间的区别,希望可以让您对Oracle过程和函数有更深
- 一、利用外键约束更新MySQL中的数据现在,最流行的开源关系型数据库管理系统非MySQL莫属,而MySQL又支持多个存储引擎,其中默认的也是
- pygame.transform 模块允许您对加载、创建后的图像进行一系列操作,比如调整图像大小、旋转图片等操作,常用方法如下所示:下面看一
- 前言没有特别幸运,那么请先特别努力,别因为懒惰而失败,还矫情地将原因归于自己倒霉。你必须特别努力,才能显得毫不费力。希望:所以说,树倒了,没
- 本文是对《Python Qt GUI快速编程》的第9章的扩展对话框例子Find and replace用Python3+PyQt5+Qt D
- 一、http请求1、http请求方式:get和postget一般用于获取/查询资源信息,在浏览器中直接输入url+请求参数点击enter之后
- 我最近用MYSQL数据库挺多的,发现了一些非常有用的小玩意,今天拿出来分享到大家,希望对你会有所帮助。1.group_concat在我们平常
- 回想自己从事Web方面的开发已经有6-7年,对于各种Web技术都已经非常熟悉.可是,身为程序员的我对于制作Web表单界面的事着实心痛。心痛1
- 案例一:运行下面的代码结果是什么?class Person: def run(self): &nbs
- 前言事情是这样的:今天晚上,女朋友让我十二点催她睡觉。不过,可是我实在太困了,熬不下去…… 是吧
- 一、MYSQL的索引索引(Index):帮助Mysql高效获取数据的一种数据结构。用于提高查找效率,可以比作字典。可以简单理解为排好序的快速
- 前言一些公司内部的CMS系统存在某些内容让指定的用户有权限访问,这时候可以用django自带的权限管理进行限制,比较方便。缺点:django
- 自己也百度了一下,然后写的,分为了三个部分,见三段代码代码:主程序代码import timefrom selenium&
- 同时安装vs2005团队开发版和sql 2005企业版(downmoon原作)由于微软在vs2005vsts团队开发版中集成了sql 200
- 如下所示:def user_degree(self): degree = self.user.update_grade() &n
- SQL语句中要不要加单引号?犯了一个超级超级蠢的错误,把population写成polulation而不自知,多次提醒我找不到polulat
- 栅格系统的形成1692年,新登基的法国国王路易十四感到法国的印刷水平强差人意,因此命令成立一个管理印刷的皇家特别委员会。他们的首要任务是设计