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

假装没事ソ 提交于 2020-01-12 07:01:16

问题


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


回答1:


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




回答2:


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.




回答3:


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.




回答4:


In SQL, you can query it like:

WHERE field LIKE '10??8??0??'

Try that in your Django filter.



来源:https://stackoverflow.com/questions/8644146/django-query-how-to-write-where-field-like-10-8-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!