Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query how to write: WHERE field LIKE '10__8__0__'?

There is contains method, but it means: WHERE field LIKE '%10%'. And I need exactly WHERE field LIKE '10__8__0__'.

Thanks!

EDIT:

I mean string is '10xx8xx0xx', where x - any symbol

like image 596
Vitalii Ponomar Avatar asked Dec 27 '11 11:12

Vitalii Ponomar


People also ask

How do you query a many to many relationship in Django?

When querying many-to-many relationships, avoid using multiple filter() methods, make use of Q() objects instead. You can check the SQL query of a QuerySet with str(queryset. query) . Check the performance of recently executed SQL queries with django.


3 Answers

The easiest way to do the search you intend to do is by regular expression:

MyModel.objects.filter(field__regex=r'^10..8..0..$')

Edit:

My solution is possibly much slower than LIKE. The problem though is that the django ORM does not allow easy access to LIKE. It'd be easiest if startswith or endswith were sufficient for your purposes.

like image 79
tback Avatar answered Oct 27 '22 15:10

tback


You can do this with django-like:

MyModel.objects.filter(field__like='10%8%0%')

Also I created a related ticket on the Django project site

like image 28
Goin Avatar answered Oct 27 '22 15:10

Goin


You can use extra to do this:

MyModel.objects.extra(where=["column_name LIKE '%10%"])

Note that column_name is the column name in the database, rather than the field name in your Django model. In many cases, the field name and column name will be the same, but if they differ, take care to use the column name.

like image 35
Jimothy Avatar answered Oct 27 '22 16:10

Jimothy