Last active
April 25, 2020 23:38
-
-
Save marcelobbfonseca/ea7a29fcc54d35f9f6334fc98683b04e to your computer and use it in GitHub Desktop.
Django model find by name example
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 | |
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