Django: how to filter model field values ​​out of space?

I asked this question before. Maybe due to the lack of the desired answers, again, I see this as an opportunity to explain my problem well in this space.

Please note: I am using a MySQL database

I have a model called City . It contains an identifier, a name .

id      name
1       New York
2       New India
3       New USA
4       New UK

Now using the syntax below

Please note: As an example, I set a static value, namely New in the syntax below. In the end, it should be a dynamic value.

City.objects.filter (name__icontains = "New")

Obviously, I get New York, New India, New USA, New United Kingdom

.


. -. newyork () New York () NEWYORK () NEw yOrk () - , .

City.objects.filter(name__iregex= "newyork")  ?// How to fix this one

CURRENT OUTPUT is:
[]

DESIRED OUTPUT is:
New York
+4
3

.

from django.db.models import Transform

class SpaceRemovedValue(Transform):
    lookup_name = 'nospaces'

    def as_sql(self, compiler, connection):
        lhs, params = compiler.compile(self.lhs)
        return "REPLACE(%s, ' ', '')" % lhs, params

from django.db.models import CharField
CharField.register_lookup(SpaceRemovedValue)

:

City.objects.filter(name__nospaces= "newyork")

, . MySQL City; , .

, , . save, .

+5

\s* :

def insert_whitespace(string):
    s = []
    for i in range(0, len(string)):
        s.append(string[i:i+1])
    return '\\s*'.join(s)

City.objects.filter(name__iregex= insert_whitespace("newyork"))
+1

I am sure this is not the best solution, but it can help.

# Query you entire table
from myapp.models import City

cities = City.objects.all().values('name', 'id')  # If it get extra values later
user_entry = 'newyork'

def is_match(cities, user_entry):
    result_list = []
    for city in cities:
        for value in city['name'].lower().split(' '):
            if value in user_entry.lower():
                l.append(city['id'])
                break
    return result_list

# Then call
is_match(cities=cities, user_entry=user_entry)

# Should return something like this
[1L]  # A list with id of possibles matchs

A function is_matchmay be the concept of a list, but is thus more understandable.

This will be more inefficient with big data, but may give you an idea to get started.

+1
source

Source: https://habr.com/ru/post/1589216/


All Articles