简体   繁体   中英

Is there any way to make Django's get_or_create() to create an object without saving it to database?

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?

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

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM