PageRenderTime 71ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/django/db/models/options.py

https://github.com/Tippr/django
Python | 497 lines | 455 code | 16 blank | 26 comment | 33 complexity | 7d10a68bfdc5d48f2b09f9fbcdab0fde MD5 | raw file
  1. import re
  2. from bisect import bisect
  3. from django.conf import settings
  4. from django.db.models.related import RelatedObject
  5. from django.db.models.fields.related import ManyToManyRel
  6. from django.db.models.fields import AutoField, FieldDoesNotExist
  7. from django.db.models.fields.proxy import OrderWrt
  8. from django.db.models.loading import get_models, app_cache_ready
  9. from django.utils.translation import activate, deactivate_all, get_language, string_concat
  10. from django.utils.encoding import force_unicode, smart_str
  11. from django.utils.datastructures import SortedDict
  12. # Calculate the verbose_name by converting from InitialCaps to "lowercase with spaces".
  13. get_verbose_name = lambda class_name: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', ' \\1', class_name).lower().strip()
  14. DEFAULT_NAMES = ('verbose_name', 'verbose_name_plural', 'db_table', 'ordering',
  15. 'unique_together', 'permissions', 'get_latest_by',
  16. 'order_with_respect_to', 'app_label', 'db_tablespace',
  17. 'abstract', 'managed', 'proxy', 'auto_created')
  18. class Options(object):
  19. def __init__(self, meta, app_label=None):
  20. self.local_fields, self.local_many_to_many = [], []
  21. self.virtual_fields = []
  22. self.module_name, self.verbose_name = None, None
  23. self.verbose_name_plural = None
  24. self.db_table = ''
  25. self.ordering = []
  26. self.unique_together = []
  27. self.permissions = []
  28. self.object_name, self.app_label = None, app_label
  29. self.get_latest_by = None
  30. self.order_with_respect_to = None
  31. self.db_tablespace = settings.DEFAULT_TABLESPACE
  32. self.admin = None
  33. self.meta = meta
  34. self.pk = None
  35. self.has_auto_field, self.auto_field = False, None
  36. self.abstract = False
  37. self.managed = True
  38. self.proxy = False
  39. self.proxy_for_model = None
  40. self.parents = SortedDict()
  41. self.duplicate_targets = {}
  42. self.auto_created = False
  43. # To handle various inheritance situations, we need to track where
  44. # managers came from (concrete or abstract base classes).
  45. self.abstract_managers = []
  46. self.concrete_managers = []
  47. # List of all lookups defined in ForeignKey 'limit_choices_to' options
  48. # from *other* models. Needed for some admin checks. Internal use only.
  49. self.related_fkey_lookups = []
  50. def contribute_to_class(self, cls, name):
  51. from django.db import connection
  52. from django.db.backends.util import truncate_name
  53. cls._meta = self
  54. self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS
  55. # First, construct the default values for these options.
  56. self.object_name = cls.__name__
  57. self.module_name = self.object_name.lower()
  58. self.verbose_name = get_verbose_name(self.object_name)
  59. # Next, apply any overridden values from 'class Meta'.
  60. if self.meta:
  61. meta_attrs = self.meta.__dict__.copy()
  62. for name in self.meta.__dict__:
  63. # Ignore any private attributes that Django doesn't care about.
  64. # NOTE: We can't modify a dictionary's contents while looping
  65. # over it, so we loop over the *original* dictionary instead.
  66. if name.startswith('_'):
  67. del meta_attrs[name]
  68. for attr_name in DEFAULT_NAMES:
  69. if attr_name in meta_attrs:
  70. setattr(self, attr_name, meta_attrs.pop(attr_name))
  71. elif hasattr(self.meta, attr_name):
  72. setattr(self, attr_name, getattr(self.meta, attr_name))
  73. # unique_together can be either a tuple of tuples, or a single
  74. # tuple of two strings. Normalize it to a tuple of tuples, so that
  75. # calling code can uniformly expect that.
  76. ut = meta_attrs.pop('unique_together', self.unique_together)
  77. if ut and not isinstance(ut[0], (tuple, list)):
  78. ut = (ut,)
  79. self.unique_together = ut
  80. # verbose_name_plural is a special case because it uses a 's'
  81. # by default.
  82. if self.verbose_name_plural is None:
  83. self.verbose_name_plural = string_concat(self.verbose_name, 's')
  84. # Any leftover attributes must be invalid.
  85. if meta_attrs != {}:
  86. raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys()))
  87. else:
  88. self.verbose_name_plural = string_concat(self.verbose_name, 's')
  89. del self.meta
  90. # If the db_table wasn't provided, use the app_label + module_name.
  91. if not self.db_table:
  92. self.db_table = "%s_%s" % (self.app_label, self.module_name)
  93. self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  94. def _prepare(self, model):
  95. if self.order_with_respect_to:
  96. self.order_with_respect_to = self.get_field(self.order_with_respect_to)
  97. self.ordering = ('_order',)
  98. model.add_to_class('_order', OrderWrt())
  99. else:
  100. self.order_with_respect_to = None
  101. if self.pk is None:
  102. if self.parents:
  103. # Promote the first parent link in lieu of adding yet another
  104. # field.
  105. field = self.parents.value_for_index(0)
  106. # Look for a local field with the same name as the
  107. # first parent link. If a local field has already been
  108. # created, use it instead of promoting the parent
  109. already_created = [fld for fld in self.local_fields if fld.name == field.name]
  110. if already_created:
  111. field = already_created[0]
  112. field.primary_key = True
  113. self.setup_pk(field)
  114. else:
  115. auto = AutoField(verbose_name='ID', primary_key=True,
  116. auto_created=True)
  117. model.add_to_class('id', auto)
  118. # Determine any sets of fields that are pointing to the same targets
  119. # (e.g. two ForeignKeys to the same remote model). The query
  120. # construction code needs to know this. At the end of this,
  121. # self.duplicate_targets will map each duplicate field column to the
  122. # columns it duplicates.
  123. collections = {}
  124. for column, target in self.duplicate_targets.iteritems():
  125. try:
  126. collections[target].add(column)
  127. except KeyError:
  128. collections[target] = set([column])
  129. self.duplicate_targets = {}
  130. for elt in collections.itervalues():
  131. if len(elt) == 1:
  132. continue
  133. for column in elt:
  134. self.duplicate_targets[column] = elt.difference(set([column]))
  135. def add_field(self, field):
  136. # Insert the given field in the order in which it was created, using
  137. # the "creation_counter" attribute of the field.
  138. # Move many-to-many related fields from self.fields into
  139. # self.many_to_many.
  140. if field.rel and isinstance(field.rel, ManyToManyRel):
  141. self.local_many_to_many.insert(bisect(self.local_many_to_many, field), field)
  142. if hasattr(self, '_m2m_cache'):
  143. del self._m2m_cache
  144. else:
  145. self.local_fields.insert(bisect(self.local_fields, field), field)
  146. self.setup_pk(field)
  147. if hasattr(self, '_field_cache'):
  148. del self._field_cache
  149. del self._field_name_cache
  150. if hasattr(self, '_name_map'):
  151. del self._name_map
  152. def add_virtual_field(self, field):
  153. self.virtual_fields.append(field)
  154. def setup_pk(self, field):
  155. if not self.pk and field.primary_key:
  156. self.pk = field
  157. field.serialize = False
  158. def setup_proxy(self, target):
  159. """
  160. Does the internal setup so that the current model is a proxy for
  161. "target".
  162. """
  163. self.pk = target._meta.pk
  164. self.proxy_for_model = target
  165. self.db_table = target._meta.db_table
  166. def __repr__(self):
  167. return '<Options for %s>' % self.object_name
  168. def __str__(self):
  169. return "%s.%s" % (smart_str(self.app_label), smart_str(self.module_name))
  170. def verbose_name_raw(self):
  171. """
  172. There are a few places where the untranslated verbose name is needed
  173. (so that we get the same value regardless of currently active
  174. locale).
  175. """
  176. lang = get_language()
  177. deactivate_all()
  178. raw = force_unicode(self.verbose_name)
  179. activate(lang)
  180. return raw
  181. verbose_name_raw = property(verbose_name_raw)
  182. def _fields(self):
  183. """
  184. The getter for self.fields. This returns the list of field objects
  185. available to this model (including through parent models).
  186. Callers are not permitted to modify this list, since it's a reference
  187. to this instance (not a copy).
  188. """
  189. try:
  190. self._field_name_cache
  191. except AttributeError:
  192. self._fill_fields_cache()
  193. return self._field_name_cache
  194. fields = property(_fields)
  195. def get_fields_with_model(self):
  196. """
  197. Returns a sequence of (field, model) pairs for all fields. The "model"
  198. element is None for fields on the current model. Mostly of use when
  199. constructing queries so that we know which model a field belongs to.
  200. """
  201. try:
  202. self._field_cache
  203. except AttributeError:
  204. self._fill_fields_cache()
  205. return self._field_cache
  206. def _fill_fields_cache(self):
  207. cache = []
  208. for parent in self.parents:
  209. for field, model in parent._meta.get_fields_with_model():
  210. if model:
  211. cache.append((field, model))
  212. else:
  213. cache.append((field, parent))
  214. cache.extend([(f, None) for f in self.local_fields])
  215. self._field_cache = tuple(cache)
  216. self._field_name_cache = [x for x, _ in cache]
  217. def _many_to_many(self):
  218. try:
  219. self._m2m_cache
  220. except AttributeError:
  221. self._fill_m2m_cache()
  222. return self._m2m_cache.keys()
  223. many_to_many = property(_many_to_many)
  224. def get_m2m_with_model(self):
  225. """
  226. The many-to-many version of get_fields_with_model().
  227. """
  228. try:
  229. self._m2m_cache
  230. except AttributeError:
  231. self._fill_m2m_cache()
  232. return self._m2m_cache.items()
  233. def _fill_m2m_cache(self):
  234. cache = SortedDict()
  235. for parent in self.parents:
  236. for field, model in parent._meta.get_m2m_with_model():
  237. if model:
  238. cache[field] = model
  239. else:
  240. cache[field] = parent
  241. for field in self.local_many_to_many:
  242. cache[field] = None
  243. self._m2m_cache = cache
  244. def get_field(self, name, many_to_many=True):
  245. """
  246. Returns the requested field by name. Raises FieldDoesNotExist on error.
  247. """
  248. to_search = many_to_many and (self.fields + self.many_to_many) or self.fields
  249. for f in to_search:
  250. if f.name == name:
  251. return f
  252. raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
  253. def get_field_by_name(self, name):
  254. """
  255. Returns the (field_object, model, direct, m2m), where field_object is
  256. the Field instance for the given name, model is the model containing
  257. this field (None for local fields), direct is True if the field exists
  258. on this model, and m2m is True for many-to-many relations. When
  259. 'direct' is False, 'field_object' is the corresponding RelatedObject
  260. for this field (since the field doesn't have an instance associated
  261. with it).
  262. Uses a cache internally, so after the first access, this is very fast.
  263. """
  264. try:
  265. try:
  266. return self._name_map[name]
  267. except AttributeError:
  268. cache = self.init_name_map()
  269. return cache[name]
  270. except KeyError:
  271. raise FieldDoesNotExist('%s has no field named %r'
  272. % (self.object_name, name))
  273. def get_all_field_names(self):
  274. """
  275. Returns a list of all field names that are possible for this model
  276. (including reverse relation names). This is used for pretty printing
  277. debugging output (a list of choices), so any internal-only field names
  278. are not included.
  279. """
  280. try:
  281. cache = self._name_map
  282. except AttributeError:
  283. cache = self.init_name_map()
  284. names = cache.keys()
  285. names.sort()
  286. # Internal-only names end with "+" (symmetrical m2m related names being
  287. # the main example). Trim them.
  288. return [val for val in names if not val.endswith('+')]
  289. def init_name_map(self):
  290. """
  291. Initialises the field name -> field object mapping.
  292. """
  293. cache = {}
  294. # We intentionally handle related m2m objects first so that symmetrical
  295. # m2m accessor names can be overridden, if necessary.
  296. for f, model in self.get_all_related_m2m_objects_with_model():
  297. cache[f.field.related_query_name()] = (f, model, False, True)
  298. for f, model in self.get_all_related_objects_with_model():
  299. cache[f.field.related_query_name()] = (f, model, False, False)
  300. for f, model in self.get_m2m_with_model():
  301. cache[f.name] = (f, model, True, True)
  302. for f, model in self.get_fields_with_model():
  303. cache[f.name] = (f, model, True, False)
  304. if app_cache_ready():
  305. self._name_map = cache
  306. return cache
  307. def get_add_permission(self):
  308. return 'add_%s' % self.object_name.lower()
  309. def get_change_permission(self):
  310. return 'change_%s' % self.object_name.lower()
  311. def get_delete_permission(self):
  312. return 'delete_%s' % self.object_name.lower()
  313. def get_all_related_objects(self, local_only=False, include_hidden=False):
  314. return [k for k, v in self.get_all_related_objects_with_model(
  315. local_only=local_only, include_hidden=include_hidden)]
  316. def get_all_related_objects_with_model(self, local_only=False,
  317. include_hidden=False):
  318. """
  319. Returns a list of (related-object, model) pairs. Similar to
  320. get_fields_with_model().
  321. """
  322. try:
  323. self._related_objects_cache
  324. except AttributeError:
  325. self._fill_related_objects_cache()
  326. predicates = []
  327. if local_only:
  328. predicates.append(lambda k, v: not v)
  329. if not include_hidden:
  330. predicates.append(lambda k, v: not k.field.rel.is_hidden())
  331. return filter(lambda t: all([p(*t) for p in predicates]),
  332. self._related_objects_cache.items())
  333. def _fill_related_objects_cache(self):
  334. cache = SortedDict()
  335. parent_list = self.get_parent_list()
  336. for parent in self.parents:
  337. for obj, model in parent._meta.get_all_related_objects_with_model(include_hidden=True):
  338. if (obj.field.creation_counter < 0 or obj.field.rel.parent_link) and obj.model not in parent_list:
  339. continue
  340. if not model:
  341. cache[obj] = parent
  342. else:
  343. cache[obj] = model
  344. for klass in get_models(include_auto_created=True, only_installed=False):
  345. for f in klass._meta.local_fields:
  346. if f.rel and not isinstance(f.rel.to, basestring) and self == f.rel.to._meta:
  347. cache[RelatedObject(f.rel.to, klass, f)] = None
  348. self._related_objects_cache = cache
  349. def get_all_related_many_to_many_objects(self, local_only=False):
  350. try:
  351. cache = self._related_many_to_many_cache
  352. except AttributeError:
  353. cache = self._fill_related_many_to_many_cache()
  354. if local_only:
  355. return [k for k, v in cache.items() if not v]
  356. return cache.keys()
  357. def get_all_related_m2m_objects_with_model(self):
  358. """
  359. Returns a list of (related-m2m-object, model) pairs. Similar to
  360. get_fields_with_model().
  361. """
  362. try:
  363. cache = self._related_many_to_many_cache
  364. except AttributeError:
  365. cache = self._fill_related_many_to_many_cache()
  366. return cache.items()
  367. def _fill_related_many_to_many_cache(self):
  368. cache = SortedDict()
  369. parent_list = self.get_parent_list()
  370. for parent in self.parents:
  371. for obj, model in parent._meta.get_all_related_m2m_objects_with_model():
  372. if obj.field.creation_counter < 0 and obj.model not in parent_list:
  373. continue
  374. if not model:
  375. cache[obj] = parent
  376. else:
  377. cache[obj] = model
  378. for klass in get_models(only_installed=False):
  379. for f in klass._meta.local_many_to_many:
  380. if f.rel and not isinstance(f.rel.to, basestring) and self == f.rel.to._meta:
  381. cache[RelatedObject(f.rel.to, klass, f)] = None
  382. if app_cache_ready():
  383. self._related_many_to_many_cache = cache
  384. return cache
  385. def get_base_chain(self, model):
  386. """
  387. Returns a list of parent classes leading to 'model' (order from closet
  388. to most distant ancestor). This has to handle the case were 'model' is
  389. a granparent or even more distant relation.
  390. """
  391. if not self.parents:
  392. return
  393. if model in self.parents:
  394. return [model]
  395. for parent in self.parents:
  396. res = parent._meta.get_base_chain(model)
  397. if res:
  398. res.insert(0, parent)
  399. return res
  400. raise TypeError('%r is not an ancestor of this model'
  401. % model._meta.module_name)
  402. def get_parent_list(self):
  403. """
  404. Returns a list of all the ancestor of this model as a list. Useful for
  405. determining if something is an ancestor, regardless of lineage.
  406. """
  407. result = set()
  408. for parent in self.parents:
  409. result.add(parent)
  410. result.update(parent._meta.get_parent_list())
  411. return result
  412. def get_ancestor_link(self, ancestor):
  413. """
  414. Returns the field on the current model which points to the given
  415. "ancestor". This is possible an indirect link (a pointer to a parent
  416. model, which points, eventually, to the ancestor). Used when
  417. constructing table joins for model inheritance.
  418. Returns None if the model isn't an ancestor of this one.
  419. """
  420. if ancestor in self.parents:
  421. return self.parents[ancestor]
  422. for parent in self.parents:
  423. # Tries to get a link field from the immediate parent
  424. parent_link = parent._meta.get_ancestor_link(ancestor)
  425. if parent_link:
  426. # In case of a proxied model, the first link
  427. # of the chain to the ancestor is that parent
  428. # links
  429. return self.parents[parent] or parent_link
  430. def get_ordered_objects(self):
  431. "Returns a list of Options objects that are ordered with respect to this object."
  432. if not hasattr(self, '_ordered_objects'):
  433. objects = []
  434. # TODO
  435. #for klass in get_models(get_app(self.app_label)):
  436. # opts = klass._meta
  437. # if opts.order_with_respect_to and opts.order_with_respect_to.rel \
  438. # and self == opts.order_with_respect_to.rel.to._meta:
  439. # objects.append(opts)
  440. self._ordered_objects = objects
  441. return self._ordered_objects
  442. def pk_index(self):
  443. """
  444. Returns the index of the primary key field in the self.fields list.
  445. """
  446. return self.fields.index(self.pk)