lookups.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from django.db.models import Transform
  2. from django.db.models.lookups import PostgresOperatorLookup
  3. from django.db.models.sql.query import Query
  4. from .search import SearchVector, SearchVectorExact, SearchVectorField
  5. class DataContains(PostgresOperatorLookup):
  6. lookup_name = "contains"
  7. postgres_operator = "@>"
  8. class ContainedBy(PostgresOperatorLookup):
  9. lookup_name = "contained_by"
  10. postgres_operator = "<@"
  11. class Overlap(PostgresOperatorLookup):
  12. lookup_name = "overlap"
  13. postgres_operator = "&&"
  14. def get_prep_lookup(self):
  15. from .expressions import ArraySubquery
  16. if isinstance(self.rhs, Query):
  17. self.rhs = ArraySubquery(self.rhs)
  18. return super().get_prep_lookup()
  19. class HasKey(PostgresOperatorLookup):
  20. lookup_name = "has_key"
  21. postgres_operator = "?"
  22. prepare_rhs = False
  23. class HasKeys(PostgresOperatorLookup):
  24. lookup_name = "has_keys"
  25. postgres_operator = "?&"
  26. def get_prep_lookup(self):
  27. return [str(item) for item in self.rhs]
  28. class HasAnyKeys(HasKeys):
  29. lookup_name = "has_any_keys"
  30. postgres_operator = "?|"
  31. class Unaccent(Transform):
  32. bilateral = True
  33. lookup_name = "unaccent"
  34. function = "UNACCENT"
  35. class SearchLookup(SearchVectorExact):
  36. lookup_name = "search"
  37. def process_lhs(self, qn, connection):
  38. if not isinstance(self.lhs.output_field, SearchVectorField):
  39. config = getattr(self.rhs, "config", None)
  40. self.lhs = SearchVector(self.lhs, config=config)
  41. lhs, lhs_params = super().process_lhs(qn, connection)
  42. return lhs, lhs_params
  43. class TrigramSimilar(PostgresOperatorLookup):
  44. lookup_name = "trigram_similar"
  45. postgres_operator = "%%"
  46. class TrigramWordSimilar(PostgresOperatorLookup):
  47. lookup_name = "trigram_word_similar"
  48. postgres_operator = "%%>"
  49. class TrigramStrictWordSimilar(PostgresOperatorLookup):
  50. lookup_name = "trigram_strict_word_similar"
  51. postgres_operator = "%%>>"