我正在以 json 格式數(shù)據(jù)從外部源導入數(shù)據(jù)。我在 Person 模型中獲取和保存數(shù)據(jù),我想更新已經(jīng)存在的模型,所以我使用 update_or_create 方法但在導入期間我收到錯誤: django.db.utils.IntegrityError: UNIQUE constraint failed: managment_person.person_id。person_id必須是獨一無二的。模范人物class Person(models.Model): person_id = models.PositiveIntegerField(unique=True) code = models.CharField(max_length=255) name = models.CharField(max_length=255) def __str__(self): return self.name這是為 Person 模型導入數(shù)據(jù)的函數(shù): def get_persons(self): r = requests.get('https://path_to_data_in_json') for obj in r.json()['data']: person, created = Person.objects.update_or_create(person_id=obj['id'], code=obj['code'], name=obj['name'])
在導入功能中更新或創(chuàng)建
慕田峪9158850
2023-03-08 15:35:35