Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make django queryset ignoring white space

Tags:

django

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.

like image 580
eachone Avatar asked Nov 06 '15 04:11

eachone


People also ask

How do I do a not equal in Django QuerySet filtering?

To answer your specific question, there is no "not equal to" but that's probably because django has both "filter" and "exclude" methods available so you can always just switch the logic round to get the desired result.

Why is QuerySet lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.

Is Django QuerySet lazy?

QuerySet s are lazy Though this looks like three database hits, in fact it hits the database only once, at the last line ( print(q) ). In general, the results of a QuerySet aren't fetched from the database until you “ask” for them. When you do, the QuerySet is evaluated by accessing the database.


2 Answers

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

like image 191
Anush Devendra Avatar answered Sep 22 '22 18:09

Anush Devendra


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.

like image 30
Dheerendra Avatar answered Sep 22 '22 18:09

Dheerendra