Djang读取JSON文件

2024-04-28 11:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由scrapy生成的json文件,格式如下:

[
    {
        "area_of_interest": [
            "Pharmaceutical"
        ], 
        "department": [
            "RETAIL PHARMACY: APOTHECARY"
        ], 
        "duties": [
            "EDUCATION:"
        ], 
        "job_function": [
            "Texas Health Presbyterian Hospital Dallas is seeking a Registered Pharmacy Technician to work PRN (as needed) hours in the Retail Pharmacy. Primary hours will be weekday shifts between 9a-5p. There will be occasional 12 hr shifts. The following is required:"
        ], 
        "job_id": [
            "  56345"
        ], 
        "job_type": [
            "PRN"
        ], 
        "location": [
            "Dallas, TX, US"
        ], 
        "location_type": [
            " Texas Health Dallas"
        ], 
        "relocation": [
            "No"
        ], 
        "shift": [
            "Variable"
        ], 
        "speciality": [
            "TCH"
        ], 
        "title": [
            "Pharmacy Tech (PRN) - Retail Pharmacy"
        ], 
        "travel": [
            "NN"
        ]
    },...

我的模型是这样的:

^{pr2}$

由于我是Django的新手,我参考了很多关于如何从Django读取json文件并将数据存储到postgresql数据库的帖子和博客。但大多数帖子都是和javascript有关的,我不知道如何使用它。在

所以我的问题是,如何从json文件读取数据,并使用django将字段存储到postgresql数据库中?在

提前谢谢你


Tags: 文件jsonistypejobbewillshifts
1条回答
网友
1楼 · 发布于 2024-04-28 11:21:54

有关如何解析json的参考,请参阅json模块的doc;有关如何创建do批插入的参考,请参见bulk_create

示例代码(未测试):

# Read file 
f = open('path_to_file.json')
json_string = f.read()
f.close()

# Convert json string to python object
import json
data = json.loads(json_string)

# Create model instances for each item
items = []
for item in data:
   # create model instances...
   item = YourModel(*item)
   items.append(item)

# Create all in one query
YourModel.objects.bulk_create(items)

相关问题 更多 >