Django如何批量創(chuàng)建Model
1.前言:
將測(cè)試數(shù)據(jù)全部敲入數(shù)據(jù)庫(kù)非常繁瑣,而且如果與合作伙伴一起開(kāi)發(fā),部署,那么他們肯定也不想把時(shí)間花在一個(gè)一個(gè)錄入數(shù)據(jù)的繁瑣過(guò)程中,這時(shí)候,創(chuàng)建一個(gè)批量錄入數(shù)據(jù)的腳本(population script)就非常有必要。
2.代碼:
假設(shè)在models.py中定義的數(shù)據(jù)為下面:
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.代碼要點(diǎn)
(1)在獨(dú)立運(yùn)行django的代碼時(shí),而不是通過(guò) python manage.py runserver的方式運(yùn)行時(shí),必須使用django.setup()來(lái)引入Django項(xiàng)目的設(shè)置,而在引入設(shè)置之前還要指明 環(huán)境變量DJANGO_SETTINGS_MODULE用的是本項(xiàng)目的settings。
設(shè)置環(huán)境變量在python中常用os.environ,它返回一個(gè)字典類型,里面包含了所有環(huán)境變量的鍵值對(duì),所以在這里使用字典的內(nèi)置方法setdefault,將環(huán)境變量
'DJANGO_SETTINGS_MODULE' 設(shè)置為'tango_with_django_project.settings'(本項(xiàng)目的settings.py)。<br>參考:<a 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>
在這里,需要注意的是,如果在創(chuàng)建model instance時(shí),僅在model有默認(rèn)值的情況下可以不輸入任何kwargs,否則必須至少輸入一個(gè)值(field,如這里page的category,或者Category的name),然后該方法會(huì)帶著這個(gè)值先去找有沒(méi)有該值下的model instance,如果沒(méi)有則創(chuàng)建一個(gè)新的,返回(object,created),這里object 是新創(chuàng)建的對(duì)象的reference,created為True.
4.運(yùn)行查看
運(yùn)行python populate.py:
然后登陸admin頁(yè)面查看:
可以看到,數(shù)據(jù)全部被讀入數(shù)據(jù)庫(kù)。
以上就是Django如何批量創(chuàng)建Model的詳細(xì)內(nèi)容,更多關(guān)于Django批量創(chuàng)建Model的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- django model object序列化實(shí)例
- Django model序列化為json的方法示例
- 詳解django的serializer序列化model幾種方法
- Django model重寫(xiě)save方法及update踩坑詳解
- django Model層常用驗(yàn)證器及自定義驗(yàn)證器詳解
- django models里數(shù)據(jù)表插入數(shù)據(jù)id自增操作
- Django更新models數(shù)據(jù)庫(kù)結(jié)構(gòu)步驟
- django實(shí)現(xiàn)將后臺(tái)model對(duì)象轉(zhuǎn)換成json對(duì)象并傳遞給前端jquery
- 通過(guò)代碼簡(jiǎn)單了解django model序列化作用
相關(guān)文章
pandas數(shù)據(jù)拼接的實(shí)現(xiàn)示例
這篇文章主要介紹了pandas數(shù)據(jù)拼接的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04pyenv與virtualenv安裝實(shí)現(xiàn)python多版本多項(xiàng)目管理
這篇文章主要介紹了pyenv與virtualenv安裝實(shí)現(xiàn)python多版本多項(xiàng)目管理過(guò)程,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08詳解Anconda環(huán)境下載python包的教程(圖形界面+命令行+pycharm安裝)
這篇文章主要介紹了Anconda環(huán)境下載python包的教程(圖形界面+命令行+pycharm安裝),這篇文章很適合小白入手級(jí)別的,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-11-11Python必備技巧之Pandas數(shù)據(jù)合并函數(shù)
Pandas中一共有五個(gè)數(shù)據(jù)合并函數(shù),分別為:concat、append、merge、join、combine,本文詳細(xì)講解這五個(gè)函數(shù)的使用方法,需要的可以參考一下2022-03-03Python偽代碼分析點(diǎn)贊器實(shí)現(xiàn)原理及代碼
這篇文章主要介紹了Python偽代碼分析點(diǎn)贊器實(shí)現(xiàn)原理,本次點(diǎn)贊?rùn)C(jī)器人,主要面向電腦上的 Web 站點(diǎn),不涉及 APP 端,需要的朋友可以參考下2022-04-04python 中的paramiko模塊簡(jiǎn)介及安裝過(guò)程
這篇文章主要介紹了python 中的paramiko模塊簡(jiǎn)介及安裝過(guò)程,通過(guò)實(shí)例詳解給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2020-02-02python?reshape和transpose的區(qū)別小結(jié)
reshape()?和?transpose()?是用于改變數(shù)組或張量形狀的兩種不同方法,本文主要介紹了python?reshape和transpose的區(qū)別小結(jié),具有一定參考價(jià)值,感興趣的可以了解一下2024-02-02Python實(shí)現(xiàn)地圖可視化folium完整過(guò)程
Folium是一個(gè)基于leaflet.js的Python地圖庫(kù),其中,Leaflet是一個(gè)非常輕的前端地圖可視化庫(kù),本文重點(diǎn)給大家介紹Python實(shí)現(xiàn)地圖可視化folium完整過(guò)程,感興趣的朋友跟隨小編一起看看吧2021-05-05