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.
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.