update_or_create 在导入功能中

update_or_create in import feature

我正在以 json 格式数据从外部源导入数据。我在 Person 模型中获取和保存数据,我想更新已经存在的模型,所以我使用 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 模型导入数据的函数:

    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'])

来自关于 update_or_create

的文档

The update_or_create method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in the defaults dictionary.


obj, created = Person.objects.update_or_create(
    first_name='John', last_name='Lennon',
    defaults={'first_name': 'Bob'},
)

您应该相应地编辑您的默认设置