[Django]-In Django filter statement what's the difference between __exact and equal sign (=)?

45👍

There is no difference, the second one implies using the __exact.

From the documentation:

For example, the following two statements are equivalent:
>>> Blog.objects.get(id__exact=14)  # Explicit form
>>> Blog.objects.get(id=14)         
# __exact is implied This is for convenience, because exact 
# lookups are the common case.
👤MikeAr

28👍

You can look at the SQL that Django will execute by converting the queryset’s query property to a string:

>>> from django.contrib.auth.models import User
>>> str(User.objects.filter(username = 'name').query)
'SELECT ... WHERE `auth_user`.`username` = name '
>>> str(User.objects.filter(username__exact = 'name').query)
'SELECT ... WHERE `auth_user`.`username` = name '

So __exact makes no difference here.

2👍

This is not exactly the same as the question but can be useful for some developers.
It depends on Django database and collation. I am using mysql db and ci(case insensitive) collation and have a strange result.

If there is User "Test" and query with space in the end

In  : User.objects.filter(username__iexact="Test ")
Out : <QuerySet []>

In  : User.objects.filter(username__exact="Test ")
Out : <QuerySet [<User: Test>]>

In  : User.objects.filter(username="Test ")
Out : <QuerySet [<User: Test>]>

0👍

from django.test import TestCase

from user.factories import UserFactory
from user.models import User


class TestCaseSensitiveQueryTestCase(TestCase):

    def setUp(self):
        super().setUp()

        self.QUERY = 'case sensitive username'
        self.USERNAME = 'cAse SEnSItIVE UsErNAME'
        self.user = UserFactory(name=self.USERNAME)

    def test_implicit_exact_match(self):
        with self.assertRaises(User.DoesNotExist):
            User.objects.get(name=self.QUERY)

    def test_explicit_iexact_match(self):
        User.objects.get(name__iexact=self.QUERY)

Leave a comment