reverse_related.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 ..utils import get_blank_choice_label
  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. """Should the related object be hidden?"""
  55. return bool(self.related_name) and self.related_name[-1] == "+"
  56. @cached_property
  57. def name(self):
  58. return self.field.related_query_name()
  59. @property
  60. def remote_field(self):
  61. return self.field
  62. @property
  63. def target_field(self):
  64. """
  65. When filtering against this relation, return the field on the remote
  66. model against which the filtering should happen.
  67. """
  68. target_fields = self.path_infos[-1].target_fields
  69. if len(target_fields) > 1:
  70. raise exceptions.FieldError(
  71. "Can't use target_field for multicolumn relations."
  72. )
  73. return target_fields[0]
  74. @cached_property
  75. def related_model(self):
  76. if not self.field.model:
  77. raise AttributeError(
  78. "This property can't be accessed before self.field.contribute_to_class "
  79. "has been called."
  80. )
  81. return self.field.model
  82. @cached_property
  83. def many_to_many(self):
  84. return self.field.many_to_many
  85. @cached_property
  86. def many_to_one(self):
  87. return self.field.one_to_many
  88. @cached_property
  89. def one_to_many(self):
  90. return self.field.many_to_one
  91. @cached_property
  92. def one_to_one(self):
  93. return self.field.one_to_one
  94. def get_lookup(self, lookup_name):
  95. return self.field.get_lookup(lookup_name)
  96. def get_lookups(self):
  97. return self.field.get_lookups()
  98. def get_transform(self, name):
  99. return self.field.get_transform(name)
  100. def get_internal_type(self):
  101. return self.field.get_internal_type()
  102. @property
  103. def db_type(self):
  104. return self.field.db_type
  105. def __repr__(self):
  106. return "<%s: %s.%s>" % (
  107. type(self).__name__,
  108. self.related_model._meta.app_label,
  109. self.related_model._meta.model_name,
  110. )
  111. @property
  112. def identity(self):
  113. return (
  114. self.field,
  115. self.model,
  116. self.related_name,
  117. self.related_query_name,
  118. make_hashable(self.limit_choices_to),
  119. self.parent_link,
  120. self.on_delete,
  121. self.symmetrical,
  122. self.multiple,
  123. )
  124. def __eq__(self, other):
  125. if not isinstance(other, self.__class__):
  126. return NotImplemented
  127. return self.identity == other.identity
  128. def __hash__(self):
  129. return hash(self.identity)
  130. def __getstate__(self):
  131. state = self.__dict__.copy()
  132. # Delete the path_infos cached property because it can be recalculated
  133. # at first invocation after deserialization. The attribute must be
  134. # removed because subclasses like ManyToOneRel may have a PathInfo
  135. # which contains an intermediate M2M table that's been dynamically
  136. # created and doesn't exist in the .models module.
  137. # This is a reverse relation, so there is no reverse_path_infos to
  138. # delete.
  139. state.pop("path_infos", None)
  140. return state
  141. def get_choices(
  142. self,
  143. include_blank=True,
  144. blank_choice=None,
  145. limit_choices_to=None,
  146. ordering=(),
  147. ):
  148. """
  149. Return choices with a default blank choices included, for use
  150. as <select> choices for this field.
  151. Analog of django.db.models.fields.Field.get_choices(), provided
  152. initially for utilization by RelatedFieldListFilter.
  153. """
  154. if blank_choice is None:
  155. blank_choice = [("", get_blank_choice_label())]
  156. limit_choices_to = limit_choices_to or self.limit_choices_to
  157. qs = self.related_model._default_manager.complex_filter(limit_choices_to)
  158. if ordering:
  159. qs = qs.order_by(*ordering)
  160. return (blank_choice if include_blank else []) + [(x.pk, str(x)) for x in qs]
  161. def get_joining_fields(self):
  162. return self.field.get_reverse_joining_fields()
  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. @cached_property
  175. def accessor_name(self):
  176. return self.get_accessor_name()
  177. def get_accessor_name(self, model=None):
  178. # This method encapsulates the logic that decides what name to give an
  179. # accessor descriptor that retrieves related many-to-one or
  180. # many-to-many objects. It uses the lowercased object_name + "_set",
  181. # but this can be overridden with the "related_name" option. Due to
  182. # backwards compatibility ModelForms need to be able to provide an
  183. # alternate model. See BaseInlineFormSet.get_default_prefix().
  184. opts = model._meta if model else self.related_model._meta
  185. model = model or self.related_model
  186. if self.multiple:
  187. # If this is a symmetrical m2m relation on self, there is no
  188. # reverse accessor.
  189. if self.symmetrical and model == self.model:
  190. return None
  191. if self.related_name:
  192. return self.related_name
  193. return opts.model_name + ("_set" if self.multiple else "")
  194. def get_path_info(self, filtered_relation=None):
  195. if filtered_relation:
  196. return self.field.get_reverse_path_info(filtered_relation)
  197. else:
  198. return self.field.reverse_path_infos
  199. @cached_property
  200. def path_infos(self):
  201. return self.get_path_info()
  202. @cached_property
  203. def cache_name(self):
  204. """
  205. Return the name of the cache key to use for storing an instance of the
  206. forward model on the reverse model.
  207. """
  208. return self.accessor_name
  209. class ManyToOneRel(ForeignObjectRel):
  210. """
  211. Used by the ForeignKey field to store information about the relation.
  212. ``_meta.get_fields()`` returns this class to provide access to the field
  213. flags for the reverse relation.
  214. Note: Because we somewhat abuse the Rel objects by using them as reverse
  215. fields we get the funny situation where
  216. ``ManyToOneRel.many_to_one == False`` and
  217. ``ManyToOneRel.one_to_many == True``. This is unfortunate but the actual
  218. ManyToOneRel class is a private API and there is work underway to turn
  219. reverse relations into actual fields.
  220. """
  221. def __init__(
  222. self,
  223. field,
  224. to,
  225. field_name,
  226. related_name=None,
  227. related_query_name=None,
  228. limit_choices_to=None,
  229. parent_link=False,
  230. on_delete=None,
  231. ):
  232. super().__init__(
  233. field,
  234. to,
  235. related_name=related_name,
  236. related_query_name=related_query_name,
  237. limit_choices_to=limit_choices_to,
  238. parent_link=parent_link,
  239. on_delete=on_delete,
  240. )
  241. self.field_name = field_name
  242. def __getstate__(self):
  243. state = super().__getstate__()
  244. state.pop("related_model", None)
  245. return state
  246. @property
  247. def identity(self):
  248. return (*super().identity, self.field_name)
  249. def get_related_field(self):
  250. """
  251. Return the Field in the 'to' object to which this relationship is tied.
  252. """
  253. field = self.model._meta.get_field(self.field_name)
  254. if not field.concrete:
  255. raise exceptions.FieldDoesNotExist(
  256. "No related field named '%s'" % self.field_name
  257. )
  258. return field
  259. def set_field_name(self):
  260. self.field_name = self.field_name or self.model._meta.pk.name
  261. class OneToOneRel(ManyToOneRel):
  262. """
  263. Used by OneToOneField to store information about the relation.
  264. ``_meta.get_fields()`` returns this class to provide access to the field
  265. flags for the reverse relation.
  266. """
  267. def __init__(
  268. self,
  269. field,
  270. to,
  271. field_name,
  272. related_name=None,
  273. related_query_name=None,
  274. limit_choices_to=None,
  275. parent_link=False,
  276. on_delete=None,
  277. ):
  278. super().__init__(
  279. field,
  280. to,
  281. field_name,
  282. related_name=related_name,
  283. related_query_name=related_query_name,
  284. limit_choices_to=limit_choices_to,
  285. parent_link=parent_link,
  286. on_delete=on_delete,
  287. )
  288. self.multiple = False
  289. class ManyToManyRel(ForeignObjectRel):
  290. """
  291. Used by ManyToManyField to store information about the relation.
  292. ``_meta.get_fields()`` returns this class to provide access to the field
  293. flags for the reverse relation.
  294. """
  295. def __init__(
  296. self,
  297. field,
  298. to,
  299. related_name=None,
  300. related_query_name=None,
  301. limit_choices_to=None,
  302. symmetrical=True,
  303. through=None,
  304. through_fields=None,
  305. db_constraint=True,
  306. ):
  307. super().__init__(
  308. field,
  309. to,
  310. related_name=related_name,
  311. related_query_name=related_query_name,
  312. limit_choices_to=limit_choices_to,
  313. )
  314. if through and not db_constraint:
  315. raise ValueError("Can't supply a through model and db_constraint=False")
  316. self.through = through
  317. if through_fields and not through:
  318. raise ValueError("Cannot specify through_fields without a through model")
  319. self.through_fields = through_fields
  320. self.symmetrical = symmetrical
  321. self.db_constraint = db_constraint
  322. @property
  323. def identity(self):
  324. return (
  325. *super().identity,
  326. self.through,
  327. make_hashable(self.through_fields),
  328. self.db_constraint,
  329. )
  330. def get_related_field(self):
  331. """
  332. Return the field in the 'to' object to which this relationship is tied.
  333. Provided for symmetry with ManyToOneRel.
  334. """
  335. opts = self.through._meta
  336. if self.through_fields:
  337. field = opts.get_field(self.through_fields[0])
  338. else:
  339. for field in opts.fields:
  340. rel = getattr(field, "remote_field", None)
  341. if rel and rel.model == self.model:
  342. break
  343. return field.foreign_related_fields[0]