有没有办法让Django的get_or_create()创建一个对象而不将其保存到数据库?

时间:2022-03-12 15:57:58

When using Django's get_or_create(), when created=True, is there any way to make it so that it creates an object without saving it to DB?

当使用Django的get_or_create()时,当created = True时,是否有任何方法可以使它创建一个对象而不将其保存到DB?

I want to take the newly created object, do some validation tests, and only save it to DB if it passes all tests.

我想获取新创建的对象,进行一些验证测试,并且只有在通过所有测试时才将其保存到DB。

2 个解决方案

#1


10  

Rather than try to make get_or_create something it's not, why not just create a new @classmethod (or use a custom manager) called get_or_new(), and then only do the save() when you want to?

为什么不只是创建一个名为get_or_new()的新的@classmethod(或使用自定义管理器),然后只在你想要的时候执行save(),而不是试图让get_or_create不是。

#2


1  

Why not override the model's save method, and have it do the tests there? Then you don't have to make sure you use the right creation method each time.

为什么不覆盖模型的保存方法,让它在那里进行测试?然后,您不必确保每次都使用正确的创建方法。

class MyModel(Model)
    def save(self):
        self.run_presave_tests()
        if self.passed_tests:
            super(MyModel, self).save()

#1


10  

Rather than try to make get_or_create something it's not, why not just create a new @classmethod (or use a custom manager) called get_or_new(), and then only do the save() when you want to?

为什么不只是创建一个名为get_or_new()的新的@classmethod(或使用自定义管理器),然后只在你想要的时候执行save(),而不是试图让get_or_create不是。

#2


1  

Why not override the model's save method, and have it do the tests there? Then you don't have to make sure you use the right creation method each time.

为什么不覆盖模型的保存方法,让它在那里进行测试?然后,您不必确保每次都使用正确的创建方法。

class MyModel(Model)
    def save(self):
        self.run_presave_tests()
        if self.passed_tests:
            super(MyModel, self).save()