Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 465
Continuation Avatar asked Dec 09 '22 18:12

Continuation


2 Answers

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?

like image 189
Peter Rowell Avatar answered May 15 '23 03:05

Peter Rowell


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()
like image 30
jcdyer Avatar answered May 15 '23 03:05

jcdyer