Django QuerySets API中__exact查询参数的作用是什么?
Hey there, let’s break down exactly what Django’s __exact QuerySet lookup does, using your test examples to make it super clear.
__exact Lookup Explained It’s the Default Exact Match Behavior
First off, __exact is Django’s explicit way to run an exact value match against your database. The key thing to note? When you use a plain field lookup (like id=15942), Django is actually using __exact behind the scenes. That’s why your first two test cases return identical results:
>>> Library.objects.filter(id = 15942) <QuerySet [<Library: bee>]> >>> Library.objects.filter(id__exact = 15942) <QuerySet [<Library: bee>]>
Same goes for your title matches—title='bee' is just shorthand for title__exact='bee':
>>> Library.objects.filter(title = 'bee') <QuerySet [<Library: bee>]> >>> Library.objects.filter(title__exact = 'bee') <QuerySet [<Library: bee>]>
Case Sensitivity Isn’t Controlled by __exact
Your tests showed that both title='Bee' and title__exact='Bee' return an empty QuerySet. That’s not because __exact ignores case—it’s because case sensitivity depends entirely on your database’s collation settings for the title column.
If your database used a case-insensitive collation (like default MySQL setups often do), __exact would match 'bee', 'Bee', and 'BEE' equally. But in your case, the collation is case-sensitive, so only the exact case ('bee') returns a hit.
When to Use __exact Explicitly
Most of the time, you won’t need to write __exact out—since the shorthand works perfectly fine. But it’s useful for clarity, especially if you’re mixing other lookups (like __contains or __icontains) in the same query. It makes your intent crystal clear to anyone reading your code later.
内容的提问来源于stack exchange,提问作者There

