Created
January 25, 2019 18:45
-
-
Save tunecrew/2b02545d66712f59032a25b0858f3449 to your computer and use it in GitHub Desktop.
Add get_or_none(...) method to your Django models
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
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