Merge pull request #10 from collerek/add_startswith

Add startswith
This commit is contained in:
collerek
2020-09-23 18:21:21 +07:00
committed by GitHub
5 changed files with 51 additions and 3 deletions

BIN
.coverage

Binary file not shown.

View File

@ -86,6 +86,11 @@ notes = await Note.objects.filter(text__icontains="mum").all()
# exclude - from ormar >= 0.3.1
notes = await Note.objects.exclude(text__icontains="mum").all()
# startswith, istartswith, endswith, iendswith - from ormar >= 0.3.3
notes = await Note.objects.filter(text__iendswith="mum.").all()
notes = await Note.objects.filter(text__istartswith="call").all()
notes = await Note.objects.filter(text__startswith="Buy").all()
# .get()
note = await Note.objects.get(id=1)

View File

@ -26,7 +26,7 @@ class UndefinedType: # pragma no cover
Undefined = UndefinedType()
__version__ = "0.3.2"
__version__ = "0.3.3"
__all__ = [
"Integer",
"BigInteger",

View File

@ -15,6 +15,10 @@ FILTER_OPERATORS = {
"iexact": "ilike",
"contains": "like",
"icontains": "ilike",
"startswith": "like",
"istartswith": "ilike",
"endswith": "like",
"iendswith": "ilike",
"in": "in_",
"gt": "__gt__",
"gte": "__ge__",
@ -169,7 +173,14 @@ class QueryClause:
) -> Tuple[str, bool]:
has_escaped_character = False
if op not in ["contains", "icontains"]:
if op not in [
"contains",
"icontains",
"startswith",
"istartswith",
"endswith",
"iendswith",
]:
return value, has_escaped_character
if isinstance(value, ormar.Model):
@ -183,7 +194,9 @@ class QueryClause:
# enable escape modifier
for char in ESCAPE_CHARACTERS:
value = value.replace(char, f"\\{char}")
value = f"%{value}%"
prefix = "%" if "start" not in op else ""
sufix = "%" if "end" not in op else ""
value = f"{prefix}{value}{sufix}"
return value, has_escaped_character

View File

@ -374,3 +374,33 @@ async def test_model_choices():
await Country.objects.create(
name=name, taxed=taxed, country_code=country_code
)
@pytest.mark.asyncio
async def test_start_and_end_filters():
async with database:
async with database.transaction(force_rollback=True):
await User.objects.create(name="Markos Uj")
await User.objects.create(name="Maqua Bigo")
await User.objects.create(name="maqo quidid")
await User.objects.create(name="Louis Figo")
await User.objects.create(name="Loordi Kami")
await User.objects.create(name="Yuuki Sami")
users = await User.objects.filter(name__startswith="Mar").all()
assert len(users) == 1
users = await User.objects.filter(name__istartswith="ma").all()
assert len(users) == 3
users = await User.objects.filter(name__istartswith="Maq").all()
assert len(users) == 2
users = await User.objects.filter(name__iendswith="AMI").all()
assert len(users) == 2
users = await User.objects.filter(name__endswith="Uj").all()
assert len(users) == 1
users = await User.objects.filter(name__endswith="igo").all()
assert len(users) == 2