Django: get the first object from a filter query or create

get_or_create() is just a convenience function so there’s nothing wrong with writing your own, like pavid has shown or

result = Model.objects.filter(field__lookup=value)[0]
if not result:
   result = Model.objects.create(...)
return result

EDIT
As suggested, changed the [:1] slice (which returns a single-entry list) after the filter to [0] (which returns the actual object). The problem with this is it will raise an exception if there is not match to the query.

This will also raise a simliar exception:

Model.objects.filter(field_lookup=value).latest()

Looking at the question again, I’m not sure whether the original poster is looking to return multiple objects/rows, or just a way to get around raising an exception when retrieving a single object/row.

Here’s another option?

results = Model.objects.filter(...)
if results.exists():
    return results
else:
    return Model.objects.create(...)

and another:

result = None
try:
    result = Model.objects.get(...)
except Model.DoesNotExist:
    result = Model.objects.create(...)

There’s nothing wrong with raising & catching exceptions!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)