Fastest way to get a not required specific record in database using Django

Viewed 68

What would be the fastest way to get a specific record, that can or cannot exists, using Django.

Some possible approaches:

results = ModelExample.objects.filter(label="example1")
if(results.exists())
   item = results.first()

results = ModelExample.objects.filter(label="example1")
if(len(results) > 0)
   item = results.first()

*** Edit ***

I was not clear on my original question, my real search is to a way to get a property from a nullable object return from a queryset, case the object exists, take the property and if does not return None.

I was looking for something similar to item?.value on JavaScript.

Fortunately @Willem help me showing the getattr(...) function on the accepted answer.

2 Answers

You can work with .first(). If the item does not exists, it will return None, so:

result = ModelExample.objects.filter(label='example1').first()
if result is None:
    # does not exists
    # …
    pass

you can make use of a one-liner to obtain a property with:

result = getattr(
    ModelExample.objects.filter(label='example1').first(),
    'name-of-the-attribute',
    None
)
Related