將 JSON 資料轉儲到 Django 模型:使用 Django 設定和命令

王林
發布: 2024-08-16 18:01:36
原創
458 人瀏覽過

Dumping JSON data to Django Models: Using Django Setup and Commands

當您使用 Django 或使用 Django Rest Framework (DRF) 的 REST API 完成網站的第一個版本時,資料需求變得最為重要。對於類似的問題,我寫了上一篇文章,其中討論了透過直接插入 SQLite 資料庫和表格將 JSON 資料轉儲到 Django 模型中的直接方法。然而,我也提到 Django 有 loaddata、dumpdata 和用於類似問題的固定裝置,但需要對框架有更多的了解。

今天,我將回顧一下學習曲線,並討論如何將普通 JSON 資料轉換為固定裝置,然後使用 loaddata 將 JSON 資料轉儲到特定模型中。同樣,如果您有一些模型資料(可以透過管理頁面等添加),那麼如何將其轉儲為固定裝置以與其他模型一起使用或在其他專案中使用。

上一篇文章分為兩部分:第一部分是資料轉儲所需的正常設置,第二部分是關於將 JSON 資料轉儲到模型中的 python 腳本。因此,請保持文章簡短,在本文中,我將從第二部分開始,您可以按照上一篇文章的第一部分來閱讀本文。因此,假設您有一個圖書應用程序,並且其中 models.py 中有 Book 模型,類似地,API 端點已準備就緒,例如(上一篇文章的 Github 存儲庫):
http://127.0.0.1:8000/api/books/1

或您只是想將資料載入到基於 Django 的網站的 Book 模型。您可以關注以下 git 儲存庫中的程式碼。
JSON 資料轉儲到模型

給定兩個儲存庫,您可以使用任何人來關注這裡的文章,您只需要以下內容:

  1. 一個正在運行的 Django 項目,具有或不帶有 API 功能的 Book 模型
  2. 一個 json 文件,其中包含根據 Book 模型的書籍資訊。

範例 1:book/models.py 中的書籍模型

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)    
    isbn = models.CharField(max_length=13, unique=True)
    pages = models.PositiveIntegerField()   
    language = models.CharField(max_length=30)

    def __str__(self):
        return self.title

登入後複製

books.json

[
  {
    "title": "Example Book 1",
    "author": "John Doe",
    "isbn": "1234567890123",
    "pages": 350,
    "language": "English"
  },
  {
    "title": "Example Book 2",
    "author": "Kumar Ajit",
    "isbn": "9876543210987",
    "pages": 280,
    "language": "Hindi"
  }
]

登入後複製

範例 2:上一篇文章中的 Book 模型

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=6, decimal_places=2)

    def __str__(self):
        return self.title
登入後複製

您可以在此處找到 data.json 檔案。

資料轉儲到模型

我們有一個正在運行的 Django 項目,其中包含一個模型 Book 和一個包含書籍資訊的額外 JSON 檔案。那麼,現在的問題是什麼?
我們希望將 JSON 資料轉儲到模型中,以便可以與 Django 網站一起使用(例如將資料傳遞到模板以顯示給使用者)或透過 API 向前端提供資料。

Django 有 loaddata、fixtures 和 dumpdata,以及管理頁面(您可以註冊模型和插入資料)和 shell(使用 SQL 或 ORM 直接操作資料庫)。然而,如果想要合併大數據或想要多次執行(通常是開發和測試期間的用例),透過固定裝置載入資料似乎會更好。

讓我們先解釋這些工具,然後深入研究 python 腳本來實現資料轉儲任務。

載入數據

$django-admin loaddata <fixture label>
登入後複製

固定裝置

fixture 是包含資料庫序列化內容的檔案集合。每個固定裝置都有一個唯一的名稱,並且組成固定裝置的檔案可以分佈在多個應用程式中的多個目錄中。 [來源]

讓我們跳到文章的後續部分,看看書籍賽程。

[
  {
    "model": "book.book",
    "pk": 40,
    "fields": {
      "title": "Example Book 1",
      "author": "John Doe",
      "isbn": "123456734890123",
      "pages": 350,
      "language": "English"
    }
  },
  {
    "model": "book.book",
    "pk": 41,
    "fields": {
      "title": "Example Book 2",
      "author": "Kumar Ajit",
      "isbn": "9876543455210987",
      "pages": 280,
      "language": "Hindi"
    }
  }
]

登入後複製

如果你有查看過fixture文件,你一定會發現它只是另一個帶有更多鍵值對的JSON文件,而這些是Django模型/表的元資料。所以,是的,你是對的,我們的目標是將 books.json 格式轉換為固定格式,以便 Django 管理工具能夠識別它並將資料轉儲到適當的表中。

現在,要建立夾具,您可以有兩種情況:1)模型中有數據,並且您想要建立夾具以供將來使用或測試等。
2) 你在模型/表中沒有數據,但在外部來源中有數據,如 json、csv 或任何其他格式,並且你想通過前面討論的命令 loaddata 在 Django 中加載該數據。 ( 這篇文章是關於這種情況的,但在最後,我們將使用 dumpdata 來比較手動和 dumpdata 輸出。)

在使用Python腳本將普通json檔案轉換為fixture格式之前,讓我們先了解一下Django如何尋找fixture檔案以及如何使用它。

共有三個興趣點和順序[來源]:

  1. 在每個已安裝應用程式的固定目錄中:這類似於 Django 專案內組織的其他目錄(例如範本或媒體或靜態資料夾)的建議。但是,您也可以提供如下所述的直接路徑。

  2. FIXTURE_DIRS 設定中列出的任何目錄

  3. In the literal path named by the fixture: Works with smaller project or app but it is better to have a proper recommended location for fixtures so it will easy to use with testing or debugging etc.

Note:One major benefit of using fixture is to apply and use compression on fixtures.

Dumpdata

This is django-admin command to output all data of table to standard output.

Note 1: Outputs to standard output all data in the database associated with the named application(s).
Note 2 : The output of dumpdata can be used as input for loaddata.(as fixture )

django-admin dumpdata [app_label[.ModelName] 
登入後複製

you can read more from this link.

Python script from simple json to Django Fixtures.

from django.apps import apps
import django
import os
import json


# Set the Django settings module
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dataloading.settings')
django.setup()

# get all models
models = apps.get_models()

# Get the model names
for model in models:
    print(model)
    print(model.__name__)

# Choose Model to create fixtures
from book.models import Book 

# Get all field names
field_names = [field.name for field in Book._meta.get_fields()]
fixture_name = "books.json"

#read the data file json, csv etc.

with open('data.json','r') as fp:
    books= json.load(fp)


books_fixture =[]
# get the pk value from model , if there is data
pk=1 
# iterate all the books in json file
for book in books:
    book_fixture={}
    # Add model name (most important for fixture)
    book_fixture['model']= 'book.book'
    pk+=1
    book_fixture['pk']=pk
    # assuming the data has same fields name as model else mapping is required
    book_fixture['fields']=book
    books_fixture.append(book_fixture)
# Writing converted Json as file for fixture

with open(fixture_name,'w') as fp:
    json.dump(books_fixture,fp)

# print(field_names)
# if __name__ =='__main__' :
    #create_book()  
登入後複製

Once your fixture is created as books.json. It time to move it /copy to suitable location (book/fixtures/book/) so that Django manager can find it easily and then run loaddata command to dump all data to Book model.

$mv books.json book/fixtures/book/
$python manage.py loaddata book/fixtures/book/books.json
登入後複製

You can also use similar script to directly write data to model sing .save() method. Below is create_book() method that can be use to insert one or more (looping) data records into Book model.

# def create_book():
#     book = Book(
#         title="This is from script",
#         author ="ajit",
#         isbn = "2024-0809",
#         pages=300,
#         language ='English'
#     )
#     book.save()
#     print(f'Book {book.title} by {book.author} created.')
登入後複製

You can also look into Dumpscript from Django-extensions for similar task.

I hope it will be helpful.

Note: The article in not properly proofread and formatted because of time constraint. So, please use it carefully and leave comments below for any errors, dobuts or questions. I will reply and edit the article overtime.

以上是將 JSON 資料轉儲到 Django 模型:使用 Django 設定和命令的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!