New feature request: exists_or_create

Add a new Manager method called exists_or_create. This method would be a compliment to the get_or_create method with the key difference being it would simply check for existence or create, rather than loading the object into memory like get_or_create does. This would give an efficiency boost when you want to only create objects if they do not exist and do not need to do anything with the object itself afterward.

Do you have numbers demonstrating how much of an improvement memory wise this would be?

I suspect the creation of the queryset object to perform the exists() query far outweighs the memory overhead of transmitting all the fields over the network and creating a model instance out of it on a match.

Also the concern about fat models containing multiple fields can also be almost entirely avoided by using only("pk") prior to calling get_or_create.

You can also use bulk_create(ignore_conflicts=True) to achieve the same ensure-exists pattern without incurring two queries.

In summary, I donā€™t see any signs demonstrating the memory saving gains a exists_or_create method would provide over current methods is worth its addition.

2 Likes

The efficiency boost Iā€™m interested in is processing speed more so than memory efficiency. Asking if a record exists in a database is much faster than pulling that record and constructing a python object with it, especially when you donā€™t need the object.

bulk_create by-passes save method and signals which may not be ideal for every use case.

The only(ā€˜pkā€™) suggestion is fine, it would just be nice to have a consistent API inline with get_or_create and update_or_create. There are other ways to achieve get_or_create/update_or_create too, yet these methods exist.

The key difference is that in those two cases, youā€™re always getting an instance of the object returned to you. It can avoid the need for an if statement to determine whether you have an object or not. (The ā€œcreatedā€ flag may not matter.)

However, with an ā€œexists_or_createā€, you always need to have an if to determine whether an object as been returned to you, in which case I donā€™t see a benefit over having an if to execute an exists query.

(As a side note of no particular importance, I canā€™t remember any situation where I would have wanted to do this, either.)

Iā€™d also be a -1 to this suggestion.

3 Likes