在Django过滤器语句中__exact和等号(=)之间有什么区别?

时间:2012-04-01 09:03:21

标签: django django-models django-orm

在Django过滤器语句中,如果我写的话有什么区别:

.filter(name__exact='Alex')

.filter(name='Alex')

由于

2 个答案:

答案 0 :(得分:25)

没有区别,第二个意味着使用__exact。

来自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.

答案 1 :(得分:15)

您可以通过将查询集的query属性转换为字符串来查看Django将执行的SQL:

>>> 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 '

所以__exact在这里没有任何区别。

相关问题