reverse_related.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. """
  2. "Rel objects" for related fields.
  3. "Rel objects" (for lack of a better name) carry information about the relation
  4. modeled by a related field and provide some utility functions. They're stored
  5. in the ``remote_field`` attribute of the field.
  6. They also act as reverse fields for the purposes of the Meta API because
  7. they're the closest concept currently available.
  8. """
  9. from django.core import exceptions
  10. from django.utils.functional import cached_property
  11. from django.utils.hashable import make_hashable
  12. from . import BLANK_CHOICE_DASH
  13. from .mixins import FieldCacheMixin
  14. class ForeignObjectRel(FieldCacheMixin):
  15. """
  16. Used by ForeignObject to store information about the relation.
  17. ``_meta.get_fields()`` returns this class to provide access to the field
  18. flags for the reverse relation.
  19. """
  20. # Field flags
  21. auto_created = True
  22. concrete = False
  23. editable = False
  24. is_relation = True
  25. # Reverse relations are always nullable (Django can't enforce that a
  26. # foreign key on the related model points to this model).
  27. null = True
  28. empty_strings_allowed = False
  29. def __init__(
  30. self,
  31. field,
  32. to,
  33. related_name=None,
  34. related_query_name=None,
  35. limit_choices_to=None,
  36. parent_link=False,
  37. on_delete=None,
  38. ):
  39. self.field = field
  40. self.model = to
  41. self.related_name = related_name
  42. self.related_query_name = related_query_name
  43. self.limit_choices_to = {} if limit_choices_to is None else limit_choices_to
  44. self.parent_link = parent_link
  45. self.on_delete = on_delete
  46. self.symmetrical = False
  47. self.multiple = True
  48. # Some of the following cached_properties can't be initialized in
  49. # __init__ as the field doesn't have its model yet. Calling these methods
  50. # before field.contribute_to_class() has been called will result in
  51. # AttributeError
  52. @cached_property
  53. def hidden(self):
  54. return self.is_hidden()
  55. @cached_property
  56. def name(self):
  57. return self.field.related_query_name()
  58. @property
  59. def remote_field(self):
  60. return self.field
  61. @property
  62. def target_field(self):
  63. """
  64. When filtering against this relation, return the field on the remote
  65. model against which the filtering should happen.
  66. """
  67. target_fields = self.path_infos[-1].target_fields
  68. if len(target_fields) > 1:
  69. raise exceptions.FieldError(
  70. "Can't use target_field for multicolumn relations."
  71. )
  72. return target_fields[0]
  73. @cached_property
  74. def related_model(self):
  75. if not self.field.model:
  76. raise AttributeError(
  77. "This property can't be accessed before self.field.contribute_to_class "
  78. "has been called."
  79. )
  80. return self.field.model
  81. @cached_property
  82. def many_to_many(self):
  83. return self.field.many_to_many
  84. @cached_property
  85. def many_to_one(self):
  86. return self.field.one_to_many
  87. @cached_property
  88. def one_to_many(self):
  89. return self.field.many_to_one
  90. @cached_property
  91. def one_to_one(self):
  92. return self.field.one_to_one
  93. def get_lookup(self, lookup_name):
  94. return self.field.get_lookup(lookup_name)
  95. def get_lookups(self):
  96. return self.field.get_lookups()
  97. def get_transform(self, name):
  98. return self.field.get_transform(name)
  99. def get_internal_type(self):
  100. return self.field.get_internal_type()
  101. @property
  102. def db_type(self):
  103. return self.field.db_type
  104. def __repr__(self):
  105. return "<%s: %s.%s>" % (
  106. type(self).__name__,
  107. self.related_model._meta.app_label,
  108. self.related_model._meta.model_name,
  109. )
  110. @property
  111. def identity(self):
  112. return (
  113. self.field,
  114. self.model,
  115. self.related_name,
  116. self.related_query_name,
  117. make_hashable(self.limit_choices_to),
  118. self.parent_link,
  119. self.on_delete,
  120. self.symmetrical,
  121. self.multiple,
  122. )
  123. def __eq__(self, other):
  124. if not isinstance(other, self.__class__):
  125. return NotImplemented
  126. return self.identity == other.identity
  127. def __hash__(self):
  128. return hash(self.identity)
  129. def __getstate__(self):
  130. state = self.__dict__.copy()
  131. # Delete the path_infos cached property because it can be recalculated
  132. # at first invocation after deserialization. The attribute must be
  133. # removed because subclasses like ManyToOneRel may have a PathInfo
  134. # which contains an intermediate M2M table that's been dynamically
  135. # created and doesn't exist in the .models module.
  136. # This is a reverse relation, so there is no reverse_path_infos to
  137. # delete.
  138. state.pop("path_infos", None)
  139. return state
  140. def get_choices(
  141. self,
  142. include_blank=True,
  143. blank_choice=BLANK_CHOICE_DASH,
  144. limit_choices_to=None,
  145. ordering=(),
  146. ):
  147. """
  148. Return choices with a default blank choices included, for use
  149. as <select> choices for this field.
  150. Analog of django.db.models.fields.Field.get_choices(), provided
  151. initially for utilization by RelatedFieldListFilter.
  152. """
  153. limit_choices_to = limit_choices_to or self.limit_choices_to
  154. qs = self.related_model._default_manager.complex_filter(limit_choices_to)
  155. if ordering:
  156. qs = qs.order_by(*ordering)
  157. return (blank_choice if include_blank else []) + [(x.pk, str(x)) for x in qs]
  158. def is_hidden(self):
  159. """Should the related object be hidden?"""
  160. return bool(self.related_name) and self.related_name[-1] == "+"
  161. def get_joining_columns(self):
  162. return self.field.get_reverse_joining_columns()
  163. def get_extra_restriction(self, alias, related_alias):
  164. return self.field.get_extra_restriction(related_alias, alias)
  165. def set_field_name(self):
  166. """
  167. Set the related field's name, this is not available until later stages
  168. of app loading, so set_field_name is called from
  169. set_attributes_from_rel()
  170. """
  171. # By default foreign object doesn't relate to any remote field (for
  172. # example custom multicolumn joins currently have no remote field).
  173. self.field_name = None
  174. def get_accessor_name(self, model=None):
  175. # This method encapsulates the logic that decides what name to give an
  176. # accessor descriptor that retrieves related many-to-one or
  177. # many-to-many objects. It uses the lowercased object_name + "_set",
  178. # but this can be overridden with the "related_name" option. Due to
  179. # backwards compatibility ModelForms need to be able to provide an
  180. # alternate model. See BaseInlineFormSet.get_default_prefix().
  181. opts = model._meta if model else self.related_model._meta
  182. model = model or self.related_model
  183. if self.multiple:
  184. # If this is a symmetrical m2m relation on self, there is no
  185. # reverse accessor.
  186. if self.symmetrical and model == self.model:
  187. return None
  188. if self.related_name:
  189. return self.related_name
  190. return opts.model_name + ("_set" if self.multiple else "")
  191. def get_path_info(self, filtered_relation=None):
  192. if filtered_relation:
  193. return self.field.get_reverse_path_info(filtered_relation)
  194. else:
  195. return self.field.reverse_path_infos
  196. @cached_property
  197. def path_infos(self):
  198. return self.get_path_info()
  199. def get_cache_name(self):
  200. """
  201. Return the name of the cache key to use for storing an instance of the
  202. forward model on the reverse model.
  203. """
  204. return self.get_accessor_name()
  205. class ManyToOneRel(ForeignObjectRel):
  206. """
  207. Used by the ForeignKey field to store information about the relation.
  208. ``_meta.get_fields()`` returns this class to provide access to the field
  209. flags for the reverse relation.
  210. Note: Because we somewhat abuse the Rel objects by using them as reverse
  211. fields we get the funny situation where
  212. ``ManyToOneRel.many_to_one == False`` and
  213. ``ManyToOneRel.one_to_many == True``. This is unfortunate but the actual
  214. ManyToOneRel class is a private API and there is work underway to turn
  215. reverse relations into actual fields.
  216. """
  217. def __init__(
  218. self,
  219. field,
  220. to,
  221. field_name,
  222. related_name=None,
  223. related_query_name=None,
  224. limit_choices_to=None,
  225. parent_link=False,
  226. on_delete=None,
  227. ):
  228. super().__init__(
  229. field,
  230. to,
  231. related_name=related_name,
  232. related_query_name=related_query_name,
  233. limit_choices_to=limit_choices_to,
  234. parent_link=parent_link,
  235. on_delete=on_delete,
  236. )
  237. self.field_name = field_name
  238. def __getstate__(self):
  239. state = super().__getstate__()
  240. state.pop("related_model", None)
  241. return state
  242. @property
  243. def identity(self):
  244. return super().identity + (self.field_name,)
  245. def get_related_field(self):
  246. """
  247. Return the Field in the 'to' object to which this relationship is tied.
  248. """
  249. field = self.model._meta.get_field(self.field_name)
  250. if not field.concrete:
  251. raise exceptions.FieldDoesNotExist(
  252. "No related field named '%s'" % self.field_name
  253. )
  254. return field
  255. def set_field_name(self):
  256. self.field_name = self.field_name or self.model._meta.pk.name
  257. class OneToOneRel(ManyToOneRel):
  258. """
  259. Used by OneToOneField to store information about the relation.
  260. ``_meta.get_fields()`` returns this class to provide access to the field
  261. flags for the reverse relation.
  262. """
  263. def __init__(
  264. self,
  265. field,
  266. to,
  267. field_name,
  268. related_name=None,
  269. related_query_name=None,
  270. limit_choices_to=None,
  271. parent_link=False,
  272. on_delete=None,
  273. ):
  274. super().__init__(
  275. field,
  276. to,
  277. field_name,
  278. related_name=related_name,
  279. related_query_name=related_query_name,
  280. limit_choices_to=limit_choices_to,
  281. parent_link=parent_link,
  282. on_delete=on_delete,
  283. )
  284. self.multiple = False
  285. class ManyToManyRel(ForeignObjectRel):
  286. """
  287. Used by ManyToManyField to store information about the relation.
  288. ``_meta.get_fields()`` returns this class to provide access to the field
  289. flags for the reverse relation.
  290. """
  291. def __init__(
  292. self,
  293. field,
  294. to,
  295. related_name=None,
  296. related_query_name=None,
  297. limit_choices_to=None,
  298. symmetrical=True,
  299. through=None,
  300. through_fields=None,
  301. db_constraint=True,
  302. ):
  303. super().__init__(
  304. field,
  305. to,
  306. related_name=related_name,
  307. related_query_name=related_query_name,
  308. limit_choices_to=limit_choices_to,
  309. )
  310. if through and not db_constraint:
  311. raise ValueError("Can't supply a through model and db_constraint=False")
  312. self.through = through
  313. if through_fields and not through:
  314. raise ValueError("Cannot specify through_fields without a through model")
  315. self.through_fields = through_fields
  316. self.symmetrical = symmetrical
  317. self.db_constraint = db_constraint
  318. @property
  319. def identity(self):
  320. return super().identity + (
  321. self.through,
  322. make_hashable(self.through_fields),
  323. self.db_constraint,
  324. )
  325. def get_related_field(self):
  326. """
  327. Return the field in the 'to' object to which this relationship is tied.
  328. Provided for symmetry with ManyToOneRel.
  329. """
  330. opts = self.through._meta
  331. if self.through_fields:
  332. field = opts.get_field(self.through_fields[0])
  333. else:
  334. for field in opts.fields:
  335. rel = getattr(field, "remote_field", None)
  336. if rel and rel.model == self.model:
  337. break
  338. return field.foreign_related_fields[0]