Search code examples
djangomodels

Better option to check if a particular instance exists django


Which of the two is a better and efficient option to check if an instance exists. There can only be one record returned at most.

1) Use the filter option and see if it exists:

x = MyObject.objects.filter(someField=someValue).count()
if x:
    #Instance exists

2) Use get and check for exception:

try:
    x = MyObject.objects.get(someField=someValue)
except MyObject.DoesNotExist:
    #Do Something

Which of the above mentioned methods is efficient or more "Djangoic" ?


Solution

  • An even better approach would be to use .exists() to check if a particular instance exists or not.

    MyObject.objects.filter(someField=someValue).exists() # return True/False
    

    From the .exists() docs:

    It returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

    exists() is useful for searches relating to both object membership in a QuerySet and to the existence of any objects in a QuerySet, particularly in the context of a large QuerySet.

    Some examples from the docs:

    Example-1: To find whether a model with unique field is a member of QuerySet

    The most efficient method of finding whether a model with a unique field (e.g. primary_key) is a member of a QuerySet is:

    entry = Entry.objects.get(pk=123)
    
    if some_queryset.filter(pk=entry.pk).exists(): # faster
        print("Entry contained in queryset")
    

    which will be faster than the following which requires evaluating and iterating through the entire queryset:

    if entry in some_queryset: # slower 
       print("Entry contained in QuerySet")
    

    Example-2: Finding whether a queryset contains any items

    To find whether a queryset contains any items, below method

    if some_queryset.exists(): # faster
        print("There is at least one object in some_queryset")
    

    will be faster than:

    if some_queryset: # slower
        print("There is at least one object in some_queryset")
    

    ... but not by a large degree (hence needing a large queryset for efficiency gains).

    What if i also want to use the object if it exists?

    If you want to use the object also if it exists, then using .exists() is not efficient as then you will perform 2 queries. First query will be to check for the existence and 2nd query will be to get the object.