平常用ORM大部分使用的是get、filter、exclude这三种能满足基本的需求。
ORM 条件查询使用field__结合 condition 的方式来使用的,本篇讲解下exact和iexact 在使用上有什么区别。

exact 精准查询

exact使用精确的 = 查找,如果传None参数,在SQL 中会被解释为 NULL
python测试开发django-171.ORM查询之exact和iexact

>>> Product.objects.filter(name__exact='yy')
<QuerySet [<Product: Product object (2)>, <Product: Product object (5)>]>
>>> Product.objects.filter(name__exact=None)
<QuerySet []>

上面两个查询可以等价于以下SQL

select * from yoyo_product where name='yy'; 
select * from yoyo_product where name is NULL; 

filter(name__exact='yy') 实际上是等价于 filter(name='yy')

iexact 使用 like 查找

iexact 使用 like 查找,如

>>> Product.objects.filter(name__iexact='yy')
<QuerySet [<Product: Product object (2)>, <Product: Product object (5)>]>

上面查询可以等价于以下SQL

select * from yoyo_product where name like 'yy'; 

exact 和 iexact区别

exact 和 iexact 的区别实际上就是 = 和 LIKE 的区别
这两个参数会受到你的SQL的所在的安装系统有关系。如果你的是Window系统,那么就会不区分大小写,相反Linux下是区分大小写的。
这两个参数还受你的数据库的排序规则的这个参数影响。在大部分collation=utf8_general_ci 情况下都是一样的(collation 是用来对字符串比较的)
实际开发中使用 exact 和 iexact 很少,直接使用:field=xx 即可

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-27
  • 2022-12-23
  • 2022-02-24
  • 2022-12-23
  • 2022-12-23
  • 2022-01-17
猜你喜欢
  • 2022-01-31
  • 2021-09-14
  • 2022-03-08
  • 2022-01-29
  • 2021-08-20
  • 2021-06-18
  • 2021-07-27
相关资源
相似解决方案