# A common ORM pattern

**URL:** <https://forum.djangoproject.com/t/a-common-orm-pattern/2111>\
**Category:** Using Django\
**Created:** [April 26, 2020, 1:14pm UTC](https://forum.djangoproject.com/t/a-common-orm-pattern/2111 "2020-04-26T13:14:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![conor](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/conor/32/3736_2.png) [@conor](https://forum.djangoproject.com/u/conor)\
**Post date:** [April 26, 2020, 1:14pm UTC](https://forum.djangoproject.com/t/a-common-orm-pattern/2111/1 "2020-04-26T13:14:27Z")

</div>

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:

```python
if MyObject.objects.filter(name="bob").exists():
    my_var = MyObject.objects.get(name="bob")
else:
    my_var = MyObject(name="bob")
    my_var.save()

```

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:

```python
def generic_obect_create_fetch(model, **kwargs):
    if models.objects.filter(unpack **kwargs or some other technique).exists():
         # fetch the object
    else:
         # 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?

Cheers,

C

---

<div class="post-metadata">

**Author:** ![adamchainz](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/adamchainz/32/26_2.png) [@adamchainz](https://forum.djangoproject.com/u/adamchainz)\
**Post date:** [April 26, 2020, 3:04pm UTC](https://forum.djangoproject.com/t/a-common-orm-pattern/2111/2 "2020-04-26T15:04:01Z")

</div>

I believe you’re looking for [`get_or_create`](https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.get_or_create)

---

<div class="post-metadata">

**Author:** ![conor](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/conor/32/3736_2.png) [@conor](https://forum.djangoproject.com/u/conor)\
**Post date:** [April 26, 2020, 3:17pm UTC](https://forum.djangoproject.com/t/a-common-orm-pattern/2111/3 "2020-04-26T15:17:00Z")

</div>

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

Again, thanks.

Cheers,

C
