简体   繁体   English

Django - 从 JSON 文件 URL 将数据导入数据库

[英]Django - Data import from JSON file URL into Database

I'm trying to import data from a json file URL into my Django Database on a weekly basis to keep my Database up to date.我正在尝试每周将 json 文件 URL 中的数据导入我的 Django 数据库,以使我的数据库保持最新。 That Data is coming from an Importer which was written in GO and which provides me with that JSON File via a link.该数据来自一个用 GO 编写的导入器,它通过链接为我提供了 JSON 文件。

I still don't have a way to automate this or to make sure how to check if an item got updated or not and then only update those items.我仍然没有办法自动执行此操作或确保如何检查项目是否已更新,然后仅更新这些项目。 But that is not my main issue right now.但这不是我现在的主要问题。 My main issue is that i'm receiving the following error every time i try to import the data with the manage.py command:我的主要问题是每次尝试使用 manage.py 命令导入数据时都会收到以下错误:

File "\data_import\management\commands\import_from_url.py", line 45, in handle
self.import_facility_from_file()
File "\data_import\management\commands\import_from_url.py", line 21, in import_facility_from_file
Name = data_object.get('Name', None)
AttributeError: 'str' object has no attribute 'get'

This is my Code:这是我的代码:

import os
import json
from data_import.models import Facility
from django.core.management.base import BaseCommand
from datetime import datetime
from jsontest.settings import BASE_DIR, STATIC_URL


class Command(BaseCommand):
    def import_facility_from_file(self):
        print(BASE_DIR)
        data_folder = os.path.join(BASE_DIR, 'import_data', 'resources')

        for data_file in os.listdir(data_folder):
            with open(os.path.join(data_folder, data_file), encoding='utf-8') as data_file:
                data = json.loads(data_file.read())
                for data_object in data:
                    Name = data_object.get('Name', None)
                    IssuedNumber = data_object.get('IssuedNumber', None)
                    release_year = datetime.now()

                    try:
                        Facility, created = Facility.objects.get_or_create(
                            Name=Name,
                            IssuedNumber=IssuedNumber,
                            release_year=release_year
                        )
                        if created:
                            Facility.save()
                            display_format = "\Facility, {}, has been saved."
                            print(display_format.format(Facility))
                    except Exception as ex:
                        print(str(ex))
                        msg = "\n\nSomething went wrong saving this Facility: {}\n{}".format(Name, str(ex))
                        print(msg)


    def handle(self, *args, **options):
        """
        Call the function to import data
        """
        self.import_facility_from_file()

The JSON looks like this: JSON 看起来像这样:

{"00016ed7be4d872aseddsf6f36bfsdfd647f3eb41cadedd2130bdfsdfsdf6fbbbf24c2f1a64d2cf34ac4e03aaa30309816f98a7389b2bb324a2":{"UUID":"00016ed7be4d872aseddsf6f36bfsdfd647f3eb41cadedd2130bdfsdfsdf6fbbbf24c2f1a64d2cf34ac4e03aaa30309816f98a7389b2bb324a2","Name":"SENIOR CARE","IssuedNumber":"123456","Licensee":"SENIOR CARE","Email":"test@dfjksdajfkljklsd.com","AdministratorName":"Tester","TelephoneNumber":"(123) 456-789101112","AddressInfo":{"PrimaryAddress":"123 Test Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TESTSTATE","PostalCode":"12345","Geolocation":"11.1111,-11.1111"},"Capacity":1,"MostRecentLicenseTimestamp":1234567891,"ClosedTimestamp":0,"InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0},"Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}},

You're treating an str object like a dictionary:您将 str object 视为字典:

AttributeError: 'str' object has no attribute 'get'

Why does this happen?为什么会这样? When you iterate over the JSON, the outer object is a dictionary:当您遍历 JSON 时,外部 object 是一个字典:

data = json.loads(data_file.read())

(If you come from a JavaScript background, a dictionary is like an object.) (如果您来自 JavaScript 背景,字典就像 object。)

Then, you iterate over the dictionary:然后,您遍历字典:

for data_object in data:

When you iterate over a dictionary, you iterate over its keys.当您遍历字典时,您会遍历它的键。 data_object is a string, because the keys of this dictionary are strings. data_object是一个字符串,因为这个字典的键是字符串。

Then you call .get() on the string:然后你在字符串上调用.get()

Name = data_object.get('Name', None)

That is only defined for dictionaries, and not strings.这仅针对字典定义,而不是字符串。

What you want to do is to iterate over the values of the dictionary.您想要做的是迭代字典的值。 How do you do this?你怎么做到这一点?

data = json.loads(data_file.read())
for data_object in data.values():

Or, if you want the keys and values at the same time:或者,如果您同时需要键和值:

data = json.loads(data_file.read())
for key, data_object in data.items():

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM