[Django]-Model.objects.get() or None

69๐Ÿ‘

โœ…

How about this:

obj = Model.objects.filter(id=1).first()

now if no object with id=1 exists obj would be None

Ref: https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.query.QuerySet.first

๐Ÿ‘คGaurav

3๐Ÿ‘

If you are using it in a web request, and you want to return a 404 if the object does not exist you can use

from django.shortcuts import get_object_or_404
get_object_or_404(Mode, pk=1)
๐Ÿ‘คJoseP

2๐Ÿ‘

How about this?

model_to_find = next(iter(Model.objects.filter(id=1)), None)
๐Ÿ‘คallan

1๐Ÿ‘

i think better to reuse Django functionality as much as possible, and django has 99% similar func get_object_or_404 which just raises Http404

from django.shortcuts import get_object_or_404

def get_or_none(model_or_qs, **kwargs):
    try:
        return get_object_or_404(model_or_qs, **kwargs)
    except Http404:
        return None

Some tests cases that shows that code can be used for Model, Queryset, RelatedManager

[in tests one User can Have multiple Contacts]

    @test_for(get_or_none)
    def test_get_or_none_for_model(self):
        self.assertEqual(self.user, get_or_none(User, pk=self.user.pk))
        self.assertEqual(None, get_or_none(User, pk=777))

    @test_for(get_or_none)
    def test_get_or_none_for_queryset_and_manager(self):
        contact = ContactFactory(user=self.user)
        self.assertEqual(self.user, get_or_none(User.objects, pk=self.user.pk))
        self.assertEqual(self.user, get_or_none(User.objects.all(), pk=self.user.pk))
        self.assertEqual(contact, get_or_none(Contact.objects.filter(user=self.user)))
        self.assertEqual(contact, get_or_none(self.user.contacts))
        self.assertEqual(None, get_or_none(User.objects.all(), pk=777))
        self.assertEqual(None, get_or_none(self.user.contacts, pk=777))
๐Ÿ‘คpymen

0๐Ÿ‘

get_object_or_404

in your model do . . .

@models.permalink
def get_absolute_url(self):
    return "/blog/%s/" self.slug
๐Ÿ‘คeusid

Leave a comment