PageRenderTime 46ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/haystack/utils/__init__.py

http://github.com/toastdriven/django-haystack
Python | 86 lines | 46 code | 24 blank | 16 comment | 10 complexity | 739e3c99b6ee109e7de19581f773cd48 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. # encoding: utf-8
  2. import importlib
  3. import re
  4. from django.conf import settings
  5. from haystack.constants import ID, DJANGO_CT, DJANGO_ID
  6. from haystack.utils.highlighting import Highlighter
  7. IDENTIFIER_REGEX = re.compile("^[\w\d_]+\.[\w\d_]+\.[\w\d-]+$")
  8. def default_get_identifier(obj_or_string):
  9. """
  10. Get an unique identifier for the object or a string representing the
  11. object.
  12. If not overridden, uses <app_label>.<object_name>.<pk>.
  13. """
  14. if isinstance(obj_or_string, str):
  15. if not IDENTIFIER_REGEX.match(obj_or_string):
  16. raise AttributeError(
  17. "Provided string '%s' is not a valid identifier." % obj_or_string
  18. )
  19. return obj_or_string
  20. return "%s.%s" % (get_model_ct(obj_or_string), obj_or_string._get_pk_val())
  21. def _lookup_identifier_method():
  22. """
  23. If the user has set HAYSTACK_IDENTIFIER_METHOD, import it and return the method uncalled.
  24. If HAYSTACK_IDENTIFIER_METHOD is not defined, return haystack.utils.default_get_identifier.
  25. This always runs at module import time. We keep the code in a function
  26. so that it can be called from unit tests, in order to simulate the re-loading
  27. of this module.
  28. """
  29. if not hasattr(settings, "HAYSTACK_IDENTIFIER_METHOD"):
  30. return default_get_identifier
  31. module_path, method_name = settings.HAYSTACK_IDENTIFIER_METHOD.rsplit(".", 1)
  32. try:
  33. module = importlib.import_module(module_path)
  34. except ImportError:
  35. raise ImportError(
  36. "Unable to import module '%s' provided for HAYSTACK_IDENTIFIER_METHOD."
  37. % module_path
  38. )
  39. identifier_method = getattr(module, method_name, None)
  40. if not identifier_method:
  41. raise AttributeError(
  42. "Provided method '%s' for HAYSTACK_IDENTIFIER_METHOD does not exist in '%s'."
  43. % (method_name, module_path)
  44. )
  45. return identifier_method
  46. get_identifier = _lookup_identifier_method()
  47. def get_model_ct_tuple(model):
  48. # Deferred models should be identified as if they were the underlying model.
  49. model_name = (
  50. model._meta.concrete_model._meta.model_name
  51. if hasattr(model, "_deferred") and model._deferred
  52. else model._meta.model_name
  53. )
  54. return (model._meta.app_label, model_name)
  55. def get_model_ct(model):
  56. return "%s.%s" % get_model_ct_tuple(model)
  57. def get_facet_field_name(fieldname):
  58. if fieldname in [ID, DJANGO_ID, DJANGO_CT]:
  59. return fieldname
  60. return "%s_exact" % fieldname