Django只更新模型实例中的空行

2024-10-01 05:00:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在循环浏览一个dicts列表,并根据dicts创建模型(日志)。他们与研究人员有着多对多的关系。你知道吗

每个dict都是这样的

 {'abbreviation': 'Front. Artif. Intell. Appl.',
  'journal_type': 'k',
  'title': 'Frontiers in Artificial Intelligence and Applications'}

但是,这个列表中有重复项,这很好,我手动检查它们是否存在,如果存在,我不会为它创建新模型。你知道吗

但是。问题是,dicts列表中的条目有重复项,并且不同程度地缺少列。例如

条目123

{'abbreviation': 'Front. Artif. Intell. Appl.',
      'journal_type': 'k',
      'title': 'Frontiers in Artificial Intelligence and Applications'}

条目124

{'abbreviation': 'Front. Artif. Intell. Appl.',
 'issn':123,
      'journal_type': 'k',
      'title': 'Frontiers in Artificial Intelligence and Applications'}

如你所见,124比123更“完整”。你知道吗

在123点,我已经从这个散列中创建了journal对象。但是,我想用124中的新字段更新同一行(在本例中,用issn更新行)

正确的方法是什么?:)


Tags: andin列表titletypejournalintelligencefront
1条回答
网友
1楼 · 发布于 2024-10-01 05:00:52

找到一个总是存在的列,它在数据库中也可以被认为是唯一的(考虑LogicalKey列)。你知道吗

for entry in entries:
  try:
    record = Model.objects.get(logical_key = entry['logical_key')
    for k,v in entry.items():
      if record._meta.get_field(k) is None:
        setattr(record,k,v)
    record.save()
  except:
    Model.objects.create(field1=entry['field1'],...)

相关问题 更多 >