Skip to content

Instantly share code, notes, and snippets.

@c4urself
Created June 16, 2011 08:30
Show Gist options
  • Save c4urself/1028891 to your computer and use it in GitHub Desktop.
Save c4urself/1028891 to your computer and use it in GitHub Desktop.
Get First Or None
def get_first_or_none(qs):
"""
Gets first item of queryset or None,
queryset can be QuerySet, RelatedManager,
Model, or object/Model instance.
Examples:
class Pizza(models.Model):
name = models.CharField(max_length=50)
toppings = models.ForeignKey('test.Topping')
class Topping(models.Model):
name = models.CharField(max_length=50)
# related fields
first_topping = get_first_or_none(self.toppings)
# model
my_pizza = get_first_or_none(Pizza)
# queryset
p = get_first_or_none(my_pizza.toppings.filter(name__istartswith='p'))
# object, not useful here:
first_pizza = get_first_or_none(my_pizza)
"""
if isinstance(qs, models.query.QuerySet):
try:
return qs[:1][0]
except IndexError:
return None
elif isinstance(qs, models.Manager):
try:
return qs.all()[:1][0]
except IndexError:
return None
elif issubclass(qs, models.Model):
try:
return qs._default_manager.all()[:1][0]
except IndexError:
return None
elif isinstance(qs, models.Model):
# Probably not expected behavior, but could be
# useful with setting `ordering` in your model's
# Meta class.
try:
return qs._default_manager.all()[:1][0]
except IndexError:
return None
else:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment