【问题标题】:JSON file reading by DjangoDjango 读取 JSON 文件
【发布时间】:2014-03-18 11:36:19
【问题描述】:

我有一个由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"
        ]
    },...

这是我的模型的外观:

class health(models.Model):
    location = models.CharField(max_length=32)
    title = models.CharField(max_length=64)
    location_type = models.CharField(max_length=32)
    job_id = models.CharField(max_length=16)
    department = models.CharField(max_length=24)
    area_of_interest = models.CharField(max_length=32)
    job_type = models.CharField(max_length=32)
    shift = models.CharField(max_length=32)
    relocation = models.CharField(max_length=8)
    travel = models.CharField(max_length=8)
    speciality = models.CharField(max_length=32)
    job_function = models.CharField(max_length=96)
    duties = models.CharField(max_length=56)

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

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

提前谢谢你

【问题讨论】:

  • 如何将 json 导入 django?无论如何,您如何获得 json?
  • json 是从一个 scrapy 脚本生成的。我需要 django 做的就是读取这个 json 文件并将其存储在 postgresql 中。我没有将文件发送到 django。 json文件只是保存到主文件夹中的scrapy项目中。我想要 django 做的就是从其他地方访问此文件以将数据保存在数据库中。能做到吗?

标签: python json django postgresql scrapy


【解决方案1】:

参见内置json 模块的文档了解如何解析json,参见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)

【讨论】:

    猜你喜欢
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    相关资源
    最近更新 更多