Skip to content

Commit

Permalink
Cria função personalizada para que consulta use o índice
Browse files Browse the repository at this point in the history
  • Loading branch information
turicas committed Sep 5, 2020
1 parent f09ec10 commit e18f1ac
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
33 changes: 31 additions & 2 deletions core/data_models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,34 @@
import re

from django.db import models
from django.db.models.functions import Substr
from django.db.models.expressions import Expression

REGEXP_NOT_FIELD_NAME = re.compile(".*[^a-zA-Z0-9_].*")


class Substring(Expression):
"""Substring SQL function based on Django Expression (SQL with no parameters)"""

output_field = models.TextField()

def __init__(self, field_name, pos, length=None, **extra):
if not isinstance(pos, int) or (length is not None and not isinstance(length, int)):
raise ValueError("'pos' and 'length' must be integers")
elif REGEXP_NOT_FIELD_NAME.match(field_name):
raise ValueError("Invalid value for 'field_name': {}".format(repr(field_name)))

self.field_name = field_name
self.pos = pos
self.length = length

def __repr__(self):
if self.length is not None:
return 'Substring("{}", {}, {})'.format(self.field_name, self.pos, self.length)
else:
return 'Substring("{}", {})'.format(self.field_name, self.pos)

def as_sql(self, compiler, connection):
return repr(self), []


class SociosBrasilEmpresaMixin:
Expand All @@ -13,7 +42,7 @@ def branches(self, document):
"""Filtra empresas pelos 8 primeiros dígitos do CNPJ (inclui matriz e filiais)"""

prefix = document[:8]
return self.annotate(docroot=Substr("cnpj", 1, 8)).filter(docroot=prefix)
return self.annotate(docroot=Substring("cnpj", 1, 8)).filter(docroot=prefix)

def get_headquarter_or_branch(self, document):
branches = self.branches(document)
Expand Down
11 changes: 11 additions & 0 deletions core/tests/test_data_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.db import connection

from core.data_models import Substring
from core.models import Table


def test_Substring_expression():
query = Table.objects.annotate(prefix=Substring("cnpj", 1, 8)).filter(prefix="abcdefgh").query
sql, args = query.as_sql(query.compiler, connection)
assert 'Substring("cnpj", 1, 8) = %s' in sql
assert "abcdefgh" == args[-1]

0 comments on commit e18f1ac

Please sign in to comment.