views:

100

answers:

2

Okay, so I am sick of writing this...

res = Something.objects.filter(asdf=something)

if res:
  single = res[0]
else:
  single = None

if single:
  # do some stuff

I would much rather be able to do something like this:

single = Something.objects.filter(asdf=something)
if single:
  #do some stuff

I want to be able to grab a single object without testing the filtered results.

In other words, when i know there is either going to be 1 or 0 matching entries, I would like to jump right to that entry, otherwise just get a 'None'. The DoesNotExist error that goes along with .get does not always work so well when trying to compress these queries into a single line.

Is there any way to do what I have described?

+2  A: 

Create a custom Manager which encapsulates the bit you're sick of repeating as a method (with a better name than the one below) or just write a utility function which does the same without the hit to model definitions:

class MyManager(models.Manager):
    def get_or_none(self, **kwargs):
        try:
            return self.get(**kwargs)
        except self.model.DoesNotExist:
            return None

class MyModel(models.Model):
    objects = MyManager()

Usage:

MyModel.objects.get_or_none(asdf=something)
insin
Thanks, that'll work great.
Brant
+2  A: 

The django-annoying project includes a get_object_or_None shortcut which does this, although it's trivial to write it yourself.

Daniel Roseman