【发布时间】:2021-12-15 09:24:38
【问题描述】:
我想知道是否可以在不调用 save() 的情况下将对象添加到数据库。
foo = Foo.objects.create(
#fields
)
lst_bars = []
for bar in MyModel.objects.filter(
#fields
):
lst_bars.append(Bar(
foo_id=foo.id,
# fields
))
Bar.objects.bulk_create(lst_bars)
foo.save()
在这段代码中,我创建了 Foo,然后在创建 Bar 时使用它的 id 作为参考。批量创建所有 Bar 对象后,我调用 foo save。
在 foo save() 中,我调用每个 bar save(),然后汇总所有 bar 数据并填充 Foo 字段。
方法 save 总共被调用了两次,但在 create() 中我想只创建而不保存,这样当没有数据时它不会进行计算。
【问题讨论】:
标签: django django-models django-database