您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關使用Django如何實現創建批量Model,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
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就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。