【问题标题】:Add object to the database without calling save在不调用 save 的情况下将对象添加到数据库
【发布时间】: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


    【解决方案1】:

    我找到了一种调用保存而不进行计算的方法:

    def save(self, *args, **kwargs):
        self.full_clean()
        just_created = True if not self.id else False
        if not just_created:
            # make calculations
        super().save(*args, **kwargs)
    

    如果有人知道是否可以在不以另一种方式调用 save 的情况下将对象添加到数据库中(无需更改 save 方法),我将不胜感激。

    【讨论】:

    • 您不必在bulk_create 中调用save 不支持
    • 我不想在 bulk_create 中调用 save。我要做的不是在 create() -> (foo = Foo.objects.create(#fields)) 中调用 save
    • 如果你不想调用 save ,你可以在不覆盖的情况下这样做,只需调用构造函数 foo = Foo( #fiels and all...) 并推迟 save 方法
    • 但是,如果我这样做,我将无法在 Bar(foo_id=foo.id) 中使用它的 id 作为参考
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    相关资源
    最近更新 更多