Skip to content

Instantly share code, notes, and snippets.

@marcelobbfonseca
Last active April 25, 2020 23:38
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 marcelobbfonseca/ea7a29fcc54d35f9f6334fc98683b04e to your computer and use it in GitHub Desktop.
Save marcelobbfonseca/ea7a29fcc54d35f9f6334fc98683b04e to your computer and use it in GitHub Desktop.
Django model find by name example
from django.db import models
class Something(models.Model):
name = models.CharField(max_length=200)
@staticmethod
def find_by_name(name):
try:
something = Something.objects.get(name=name)
except Something.MultipleObjectsReturned:
print('Warning: Multiple objects returned in find_by_name!')
something = something.first()
except Something.DoesNotExist:
something = None
return something
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment