简体   繁体   中英

How to make django queryset ignoring white space

There's some stored in db. the column data can include one more white space like below.

Printer
-----------------------------------
   No   |  name      |   data   
-----------------------------------
    1   | 3D Printer | 1
    2   | 3d printer | 21
    3   | 3dPrinter  | 3

I want to select all of '3d printer'.

Tell me the way for this.

You can do like:

Printer.objects.extra(where=["LOWER(REPLACE(name,' ','')) = '3dprinter'"])

The obove query will first remove any space in the name and then make it lower case, next compare it with 3dprinter

Since all space in name is removed including the one after 3d , we need to compare name with just 3dprinter

I guess django doesn't support SQL REPLACE option for strings. But you can use raw sql. Here is Django doc regarding the same: https://docs.djangoproject.com/en/1.8/topics/db/sql/

And here is raw SQL query for ignoring whitespaces Query that ignore the spaces

In my opinion you should add another column in your table slug-name which will stored name without whitespaces. This way you can easily use Django ORM on your table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM