Django exists() versus DoesNotExist

if User.objects.get(pk=id).exists()

This won’t work, so the question is pretty easy to answer: This way is inferior to the ways which do work πŸ™‚

I guess you actually didn’t make a Minimal Complete Verifiable Example and so missed the error when you posted un-verified code.


So instead, I suppose you are asking about the difference between:

  • QuerySet.exists() when you have a QuerySet (e.g. from a filter operation).

    For example:

  if User.objects.filter(pk=id).exists():
      # ... do the things that need that user to exist
  • Model.objects.get(…) and catching the Model.DoesNotExist exception type (or, if you want to be more general, the parent type ObjectDoesNotExist).

    For example:

  try:
      user = User.objects.get(pk=id)
  except User.DoesNotExist:
      # ... handle the case of that user not existing

The difference is:

  • The QuerySet.exists method is on a queryset, meaning you ask it about a query (β€œare there any instances matching this query?”), and you’re not yet attempting to retrieve any specific instance.

  • The DoesNotExist exception for a model is raised when you actually attempted to retrieve one instance, and it didn’t exist.

Use whichever one correctly expresses your intention.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)