Skip to content

Instantly share code, notes, and snippets.

@tunecrew
Created January 25, 2019 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tunecrew/2b02545d66712f59032a25b0858f3449 to your computer and use it in GitHub Desktop.
Save tunecrew/2b02545d66712f59032a25b0858f3449 to your computer and use it in GitHub Desktop.
Add get_or_none(...) method to your Django models
from django.db import models
"""
add get_or_none(...) method to a Django model
usage: Thing.objects.get_or_none(thing='something')
courtesy of https://stackoverflow.com/users/245672/kaapstorm
"""
class GetOrNoneManager(models.Manager):
def get_or_none(self, **kwargs):
try:
return self.get(**kwargs)
except self.model.DoesNotExist:
return None
class Thing(models.Model):
thing = models.CharField(max_length=255)
...
objects = GetOrNoneManager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment