A common ORM pattern

I have a very common pattern in my Django app, and an importing tool which loads data into the database from an excel document.

The pattern is like this:

if MyObject.objects.filter(name="bob").exists():
    my_var = MyObject.objects.get(name="bob")
    my_var = MyObject(name="bob")

I’m trying to think of way to create some sort of generic method which can take a bunch of arguments; thinking most likely kwargs and the model. In pseudo code, it would be something like this:

def generic_obect_create_fetch(model, **kwargs):
    if models.objects.filter(unpack **kwargs or some other technique).exists():
         # fetch the object
         # create the object by using **kwargs or some other mechanism
    return the object

Would anyone know if what I’m trying to do is possible or wise, and if so, does anyone have some tips and tricks as to how I might go about this?



I believe you’re looking for get_or_create

Cheers Adam! I don’t know how I could have missed that. Such is life sometimes.

Again, thanks.