我有一个由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数据库中?
提前谢谢
答案 0 :(得分:4)
请参阅内置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)