具有 Null 值的 django bulk_create
django bulk_create with Null value
models.py
class control(models.Model):
amount = models.IntegerField()
driver = models.ForeignKey(driver, on_delete=models.CASCADE, null=True, blank=True)
views.py
controlValues = [
(1,1,1),
(2,8,None)
]
control.objects.bulk_create([
control(
id = i[0],
amount = i[1],
driver = driver(id = i[2])
) for i in controlValues], ignore_conflicts=True
)
我收到错误:
bulk_create() 禁止,以防止因未保存相关对象而导致数据丢失'driver'。
如何为驱动程序设置 Null?我正在使用 mysql.
如果值为 None
,您不应使用该对象构建 driver
模型,而应使用:
control.objects.bulk_create([
control(
id=id,
amount=amount,
driver=driver(id=dr_id) <strong>if dr_id is not None else None</strong>
) for id, amount, dr_id in controlValues],
ignore_conflicts=True
)
或更简单:
control.objects.bulk_create([
control(
id=id,
amount=amount,
<b>driver_id=dr_id</b>
) for id, amount, dr_id in controlValues],
ignore_conflicts=True
)
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from driver
to Driver
.
models.py
class control(models.Model):
amount = models.IntegerField()
driver = models.ForeignKey(driver, on_delete=models.CASCADE, null=True, blank=True)
views.py
controlValues = [
(1,1,1),
(2,8,None)
]
control.objects.bulk_create([
control(
id = i[0],
amount = i[1],
driver = driver(id = i[2])
) for i in controlValues], ignore_conflicts=True
)
我收到错误: bulk_create() 禁止,以防止因未保存相关对象而导致数据丢失'driver'。 如何为驱动程序设置 Null?我正在使用 mysql.
如果值为 None
,您不应使用该对象构建 driver
模型,而应使用:
control.objects.bulk_create([
control(
id=id,
amount=amount,
driver=driver(id=dr_id) <strong>if dr_id is not None else None</strong>
) for id, amount, dr_id in controlValues],
ignore_conflicts=True
)
或更简单:
control.objects.bulk_create([
control(
id=id,
amount=amount,
<b>driver_id=dr_id</b>
) for id, amount, dr_id in controlValues],
ignore_conflicts=True
)
Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from
todriver
Driver
.