欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django如何批量創(chuàng)建Model

 更新時間:2020年09月01日 09:50:23   作者:JohnYang  
將測試數(shù)據(jù)全部敲入數(shù)據(jù)庫非常繁瑣,這篇文章主要介紹了Django如何批量創(chuàng)建Model,幫助大家快速錄入數(shù)據(jù),感興趣的朋友可以了解下

1.前言:

將測試數(shù)據(jù)全部敲入數(shù)據(jù)庫非常繁瑣,而且如果與合作伙伴一起開發(fā),部署,那么他們肯定也不想把時間花在一個一個錄入數(shù)據(jù)的繁瑣過程中,這時候,創(chuàng)建一個批量錄入數(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的代碼時,而不是通過 python manage.py runserver的方式運(yùn)行時,必須使用django.setup()來引入Django項(xiàng)目的設(shè)置,而在引入設(shè)置之前還要指明 環(huán)境變量DJANGO_SETTINGS_MODULE用的是本項(xiàng)目的settings。

設(shè)置環(huán)境變量在python中常用os.environ,它返回一個字典類型,里面包含了所有環(huán)境變量的鍵值對,所以在這里使用字典的內(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時,僅在model有默認(rèn)值的情況下可以不輸入任何kwargs,否則必須至少輸入一個值(field,如這里page的category,或者Category的name),然后該方法會帶著這個值先去找有沒有該值下的model instance,如果沒有則創(chuàng)建一個新的,返回(object,created),這里object 是新創(chuàng)建的對象的reference,created為True.

4.運(yùn)行查看

運(yùn)行python populate.py:

然后登陸admin頁面查看:

可以看到,數(shù)據(jù)全部被讀入數(shù)據(jù)庫。

以上就是Django如何批量創(chuàng)建Model的詳細(xì)內(nèi)容,更多關(guān)于Django批量創(chuàng)建Model的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • pandas數(shù)據(jù)拼接的實(shí)現(xiàn)示例

    pandas數(shù)據(jù)拼接的實(shí)現(xiàn)示例

    這篇文章主要介紹了pandas數(shù)據(jù)拼接的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • pyenv與virtualenv安裝實(shí)現(xiàn)python多版本多項(xiàng)目管理

    pyenv與virtualenv安裝實(shí)現(xiàn)python多版本多項(xiàng)目管理

    這篇文章主要介紹了pyenv與virtualenv安裝實(shí)現(xiàn)python多版本多項(xiàng)目管理過程,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-08-08
  • python中為main方法傳參問題

    python中為main方法傳參問題

    這篇文章主要介紹了python中為main方法傳參問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • 詳解Anconda環(huán)境下載python包的教程(圖形界面+命令行+pycharm安裝)

    詳解Anconda環(huán)境下載python包的教程(圖形界面+命令行+pycharm安裝)

    這篇文章主要介紹了Anconda環(huán)境下載python包的教程(圖形界面+命令行+pycharm安裝),這篇文章很適合小白入手級別的,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-11-11
  • Python必備技巧之Pandas數(shù)據(jù)合并函數(shù)

    Python必備技巧之Pandas數(shù)據(jù)合并函數(shù)

    Pandas中一共有五個數(shù)據(jù)合并函數(shù),分別為:concat、append、merge、join、combine,本文詳細(xì)講解這五個函數(shù)的使用方法,需要的可以參考一下
    2022-03-03
  • Python偽代碼分析點(diǎn)贊器實(shí)現(xiàn)原理及代碼

    Python偽代碼分析點(diǎn)贊器實(shí)現(xiàn)原理及代碼

    這篇文章主要介紹了Python偽代碼分析點(diǎn)贊器實(shí)現(xiàn)原理,本次點(diǎn)贊機(jī)器人,主要面向電腦上的 Web 站點(diǎn),不涉及 APP 端,需要的朋友可以參考下
    2022-04-04
  • python 中的paramiko模塊簡介及安裝過程

    python 中的paramiko模塊簡介及安裝過程

    這篇文章主要介紹了python 中的paramiko模塊簡介及安裝過程,通過實(shí)例詳解給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友參考下吧
    2020-02-02
  • python?reshape和transpose的區(qū)別小結(jié)

    python?reshape和transpose的區(qū)別小結(jié)

    reshape()?和?transpose()?是用于改變數(shù)組或張量形狀的兩種不同方法,本文主要介紹了python?reshape和transpose的區(qū)別小結(jié),具有一定參考價值,感興趣的可以了解一下
    2024-02-02
  • python中關(guān)于提升工作效率的一些小技巧

    python中關(guān)于提升工作效率的一些小技巧

    這篇文章主要介紹了python中關(guān)于提升工作效率的一些小技巧,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • Python實(shí)現(xiàn)地圖可視化folium完整過程

    Python實(shí)現(xiàn)地圖可視化folium完整過程

    Folium是一個基于leaflet.js的Python地圖庫,其中,Leaflet是一個非常輕的前端地圖可視化庫,本文重點(diǎn)給大家介紹Python實(shí)現(xiàn)地圖可視化folium完整過程,感興趣的朋友跟隨小編一起看看吧
    2021-05-05

最新評論