Created
June 16, 2011 08:30
-
-
Save c4urself/1028891 to your computer and use it in GitHub Desktop.
Get First Or None
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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