Python - "cannot unpack non-iterable int object" при импорте json-данных в базу данных
Я работаю над импортером для импорта списка объектов из json файла в мою базу данных. Импорт работает. Но когда я добавил несколько дополнительных условий для обновления существующих объектов (всякий раз, когда я запускаю скрипт снова и в json-файле появляются обновленные данные), он перестал работать так, как работал изначально. Обновление работает, если у меня только 1 объект в json-файле, но если я добавляю более одного, то получаю следующую ошибку:
cannot unpack non-iterable int object
Кроме того: Вместо обновления он просто создает две дополнительные копии одного из объектов. Пытаюсь разобраться с этим уже несколько дней, но пока безуспешно.
import_facility_from_file.py
models.py
class Facility(models.Model):
UUID = models.CharField(max_length=150, null=True, blank=True)
Name = models.CharField(max_length=50, null=True, blank=True)
admin_uid = models.OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL)
IssuedNumber = models.CharField(max_length=20, null=True, blank=True)
mainimage = models.ImageField(null=True, blank=True)
Capacity = models.IntegerField(null=True, blank=True)
Licensee = models.CharField(max_length=90, null=True, blank=True)
Email = models.EmailField(max_length=100, null=True, blank=True)
AdministratorName = models.CharField(max_length=30, null=True, blank=True)
Status = models.CharField(max_length=10, null=True, blank=True)
TelephoneNumber = models.CharField(max_length=20, null=True, blank=True)
ClosedTimestamp = models.IntegerField(null=True, blank=True)
MostRecentLicenseTimestamp = models.IntegerField(null=True, blank=True)
LatestUpdateTimestamp = models.IntegerField(null=True, blank=True)
class Meta:
verbose_name_plural = "facilities"
def __str__(self):
return self.Name
class FacilityAddress(models.Model):
PrimaryAddress = models.CharField(max_length=50, null=True, blank=True)
SecondaryAddress = models.CharField(max_length=50, null=True, blank=True)
City = models.CharField(max_length=50, null=True, blank=True)
RegionOrState = models.CharField(max_length=30, null=True, blank=True)
PostalCode = models.CharField(max_length=20, null=True, blank=True)
Geolocation = models.CharField(max_length=20, null=True, blank=True)
AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE)
class Meta:
verbose_name_plural = "facility addresses"
def __str__(self):
return f"{self.PrimaryAddress} {self.City}"
class FacilityInspectionInfo(models.Model):
ComplaintRelatedVisits = models.IntegerField(null=True, blank=True)
InspectionRelatedVisits = models.IntegerField(null=True, blank=True)
NumberOfVisits = models.IntegerField(null=True, blank=True)
LastVisitTimestamp = models.IntegerField(null=True, blank=True)
InspectionInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE)
class Meta:
verbose_name_plural = "facility inspection infos"
def __str__(self):
return self.InspectionInfo.Name
class FacilityComplaints(models.Model):
ComplaintsTypeA = models.IntegerField(null=True, blank=True)
ComplaintsTypeB = models.IntegerField(null=True, blank=True)
SubstantiatedAllegations = models.IntegerField(null=True, blank=True)
TotalAllegations = models.IntegerField(null=True, blank=True)
Complaints = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE)
class Meta:
verbose_name_plural = "facility complaints"
def __str__(self):
return self.Complaints.Name
json файл
{"00016ed7be4872a19d6e16afc98a7389b2bb324a2":
{"UUID":"c26fbbbf24c2f1a64d2cf34ac4e03aaa30309816f58c397e6afc98a7389b2bb324a2","Name":"Test Facility","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test@example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","LatestUpdateTimestamp":"1362985200",
"AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0,
"InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0},
"Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}},
"00016ed7be4872a15435435435b2bb324a2":
{"UUID":"c26fbbbf24c2f1a64d2cf34ac4324234324234fc98a7389b2bb324a2","Name":"Test Facility 2","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test@example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","LatestUpdateTimestamp":"1362985200",
"AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0,
"InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0},
"Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}},
"00234324324343243afc98a7389b2bb324a2":
{"UUID":"c26fbbbf24c2f1a64d2cf34ac43242346afc98a7389b2bb324a2","Name":"Test Facility 3","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test@example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","LatestUpdateTimestamp":"1362985200",
"AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0,
"InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0},
"Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}}}
Попробуйте сделать следующее, если вы хотите создать новый объект, если не найден объект для обновления. UUID=UUID - это **kwargs, используемые для поиска обновляемого объекта, иначе он будет создан. Значения по умолчанию будут тем, чем вы хотите обновить поля. Это документировано в https://docs.djangoproject.com/en/4.0/ref/models/querysets/#update-or-create
facility, facility_created = Facility.objects.update_or_create(UUID=UUID,
defaults={
'Name': Name,
'IssuedNumber': IssuedNumber,
'Capacity': Capacity,
'Licensee': Licensee,
'Email': Email,
'AdministratorName': AdministratorName,
'TelephoneNumber': TelephoneNumber,
'ClosedTimestamp': ClosedTimestamp,
'MostRecentLicenseTimestamp': MostRecentLicenseTimestamp,
'LatestUpdateTimestamp': LatestUpdateTimestamp
}
)
Если вам нужно просто обновить объект без создания нового объекта Facility, сделайте следующее, как описано в https://docs.djangoproject.com/en/4.0/ref/models/querysets/#update, отметив, что это не вернет ни кверисет, ни объект Facility, но обновит объект Facility с заданным UUID)
Facility.objects.filter(UUID=UUID).update(
Name=Name,
IssuedNumber=IssuedNumber,
Capacity=Capacity,
Licensee=Licensee,
Email=Email,
AdministratorName=AdministratorName,
TelephoneNumber=TelephoneNumber,
ClosedTimestamp=ClosedTimestamp,
MostRecentLicenseTimestamp=MostRecentLicenseTimestamp,
LatestUpdateTimestamp=LatestUpdateTimestamp
)