You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

model_checks.py 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import inspect
  2. import types
  3. from collections import defaultdict
  4. from itertools import chain
  5. from django.apps import apps
  6. from django.conf import settings
  7. from django.core.checks import Error, Tags, Warning, register
  8. @register(Tags.models)
  9. def check_all_models(app_configs=None, **kwargs):
  10. db_table_models = defaultdict(list)
  11. errors = []
  12. if app_configs is None:
  13. models = apps.get_models()
  14. else:
  15. models = chain.from_iterable(app_config.get_models() for app_config in app_configs)
  16. for model in models:
  17. if model._meta.managed and not model._meta.proxy:
  18. db_table_models[model._meta.db_table].append(model._meta.label)
  19. if not inspect.ismethod(model.check):
  20. errors.append(
  21. Error(
  22. "The '%s.check()' class method is currently overridden by %r."
  23. % (model.__name__, model.check),
  24. obj=model,
  25. id='models.E020'
  26. )
  27. )
  28. else:
  29. errors.extend(model.check(**kwargs))
  30. if settings.DATABASE_ROUTERS:
  31. error_class, error_id = Warning, 'models.W035'
  32. error_hint = (
  33. 'You have configured settings.DATABASE_ROUTERS. Verify that %s '
  34. 'are correctly routed to separate databases.'
  35. )
  36. else:
  37. error_class, error_id = Error, 'models.E028'
  38. error_hint = None
  39. for db_table, model_labels in db_table_models.items():
  40. if len(model_labels) != 1:
  41. model_labels_str = ', '.join(model_labels)
  42. errors.append(
  43. error_class(
  44. "db_table '%s' is used by multiple models: %s."
  45. % (db_table, model_labels_str),
  46. obj=db_table,
  47. hint=(error_hint % model_labels_str) if error_hint else None,
  48. id=error_id,
  49. )
  50. )
  51. return errors
  52. def _check_lazy_references(apps, ignore=None):
  53. """
  54. Ensure all lazy (i.e. string) model references have been resolved.
  55. Lazy references are used in various places throughout Django, primarily in
  56. related fields and model signals. Identify those common cases and provide
  57. more helpful error messages for them.
  58. The ignore parameter is used by StateApps to exclude swappable models from
  59. this check.
  60. """
  61. pending_models = set(apps._pending_operations) - (ignore or set())
  62. # Short circuit if there aren't any errors.
  63. if not pending_models:
  64. return []
  65. from django.db.models import signals
  66. model_signals = {
  67. signal: name for name, signal in vars(signals).items()
  68. if isinstance(signal, signals.ModelSignal)
  69. }
  70. def extract_operation(obj):
  71. """
  72. Take a callable found in Apps._pending_operations and identify the
  73. original callable passed to Apps.lazy_model_operation(). If that
  74. callable was a partial, return the inner, non-partial function and
  75. any arguments and keyword arguments that were supplied with it.
  76. obj is a callback defined locally in Apps.lazy_model_operation() and
  77. annotated there with a `func` attribute so as to imitate a partial.
  78. """
  79. operation, args, keywords = obj, [], {}
  80. while hasattr(operation, 'func'):
  81. # The or clauses are redundant but work around a bug (#25945) in
  82. # functools.partial in Python <= 3.5.1.
  83. args.extend(getattr(operation, 'args', []) or [])
  84. keywords.update(getattr(operation, 'keywords', {}) or {})
  85. operation = operation.func
  86. return operation, args, keywords
  87. def app_model_error(model_key):
  88. try:
  89. apps.get_app_config(model_key[0])
  90. model_error = "app '%s' doesn't provide model '%s'" % model_key
  91. except LookupError:
  92. model_error = "app '%s' isn't installed" % model_key[0]
  93. return model_error
  94. # Here are several functions which return CheckMessage instances for the
  95. # most common usages of lazy operations throughout Django. These functions
  96. # take the model that was being waited on as an (app_label, modelname)
  97. # pair, the original lazy function, and its positional and keyword args as
  98. # determined by extract_operation().
  99. def field_error(model_key, func, args, keywords):
  100. error_msg = (
  101. "The field %(field)s was declared with a lazy reference "
  102. "to '%(model)s', but %(model_error)s."
  103. )
  104. params = {
  105. 'model': '.'.join(model_key),
  106. 'field': keywords['field'],
  107. 'model_error': app_model_error(model_key),
  108. }
  109. return Error(error_msg % params, obj=keywords['field'], id='fields.E307')
  110. def signal_connect_error(model_key, func, args, keywords):
  111. error_msg = (
  112. "%(receiver)s was connected to the '%(signal)s' signal with a "
  113. "lazy reference to the sender '%(model)s', but %(model_error)s."
  114. )
  115. receiver = args[0]
  116. # The receiver is either a function or an instance of class
  117. # defining a `__call__` method.
  118. if isinstance(receiver, types.FunctionType):
  119. description = "The function '%s'" % receiver.__name__
  120. elif isinstance(receiver, types.MethodType):
  121. description = "Bound method '%s.%s'" % (receiver.__self__.__class__.__name__, receiver.__name__)
  122. else:
  123. description = "An instance of class '%s'" % receiver.__class__.__name__
  124. signal_name = model_signals.get(func.__self__, 'unknown')
  125. params = {
  126. 'model': '.'.join(model_key),
  127. 'receiver': description,
  128. 'signal': signal_name,
  129. 'model_error': app_model_error(model_key),
  130. }
  131. return Error(error_msg % params, obj=receiver.__module__, id='signals.E001')
  132. def default_error(model_key, func, args, keywords):
  133. error_msg = "%(op)s contains a lazy reference to %(model)s, but %(model_error)s."
  134. params = {
  135. 'op': func,
  136. 'model': '.'.join(model_key),
  137. 'model_error': app_model_error(model_key),
  138. }
  139. return Error(error_msg % params, obj=func, id='models.E022')
  140. # Maps common uses of lazy operations to corresponding error functions
  141. # defined above. If a key maps to None, no error will be produced.
  142. # default_error() will be used for usages that don't appear in this dict.
  143. known_lazy = {
  144. ('django.db.models.fields.related', 'resolve_related_class'): field_error,
  145. ('django.db.models.fields.related', 'set_managed'): None,
  146. ('django.dispatch.dispatcher', 'connect'): signal_connect_error,
  147. }
  148. def build_error(model_key, func, args, keywords):
  149. key = (func.__module__, func.__name__)
  150. error_fn = known_lazy.get(key, default_error)
  151. return error_fn(model_key, func, args, keywords) if error_fn else None
  152. return sorted(filter(None, (
  153. build_error(model_key, *extract_operation(func))
  154. for model_key in pending_models
  155. for func in apps._pending_operations[model_key]
  156. )), key=lambda error: error.msg)
  157. @register(Tags.models)
  158. def check_lazy_references(app_configs=None, **kwargs):
  159. return _check_lazy_references(apps)