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.

related.py 67KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647
  1. import functools
  2. import inspect
  3. from functools import partial
  4. from django import forms
  5. from django.apps import apps
  6. from django.conf import SettingsReference
  7. from django.core import checks, exceptions
  8. from django.db import connection, router
  9. from django.db.backends import utils
  10. from django.db.models import Q
  11. from django.db.models.constants import LOOKUP_SEP
  12. from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
  13. from django.db.models.query_utils import PathInfo
  14. from django.db.models.utils import make_model_tuple
  15. from django.utils.functional import cached_property
  16. from django.utils.translation import gettext_lazy as _
  17. from . import Field
  18. from .mixins import FieldCacheMixin
  19. from .related_descriptors import (
  20. ForwardManyToOneDescriptor, ForwardOneToOneDescriptor,
  21. ManyToManyDescriptor, ReverseManyToOneDescriptor,
  22. ReverseOneToOneDescriptor,
  23. )
  24. from .related_lookups import (
  25. RelatedExact, RelatedGreaterThan, RelatedGreaterThanOrEqual, RelatedIn,
  26. RelatedIsNull, RelatedLessThan, RelatedLessThanOrEqual,
  27. )
  28. from .reverse_related import (
  29. ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel,
  30. )
  31. RECURSIVE_RELATIONSHIP_CONSTANT = 'self'
  32. def resolve_relation(scope_model, relation):
  33. """
  34. Transform relation into a model or fully-qualified model string of the form
  35. "app_label.ModelName", relative to scope_model.
  36. The relation argument can be:
  37. * RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case
  38. the model argument will be returned.
  39. * A bare model name without an app_label, in which case scope_model's
  40. app_label will be prepended.
  41. * An "app_label.ModelName" string.
  42. * A model class, which will be returned unchanged.
  43. """
  44. # Check for recursive relations
  45. if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
  46. relation = scope_model
  47. # Look for an "app.Model" relation
  48. if isinstance(relation, str):
  49. if "." not in relation:
  50. relation = "%s.%s" % (scope_model._meta.app_label, relation)
  51. return relation
  52. def lazy_related_operation(function, model, *related_models, **kwargs):
  53. """
  54. Schedule `function` to be called once `model` and all `related_models`
  55. have been imported and registered with the app registry. `function` will
  56. be called with the newly-loaded model classes as its positional arguments,
  57. plus any optional keyword arguments.
  58. The `model` argument must be a model class. Each subsequent positional
  59. argument is another model, or a reference to another model - see
  60. `resolve_relation()` for the various forms these may take. Any relative
  61. references will be resolved relative to `model`.
  62. This is a convenience wrapper for `Apps.lazy_model_operation` - the app
  63. registry model used is the one found in `model._meta.apps`.
  64. """
  65. models = [model] + [resolve_relation(model, rel) for rel in related_models]
  66. model_keys = (make_model_tuple(m) for m in models)
  67. apps = model._meta.apps
  68. return apps.lazy_model_operation(partial(function, **kwargs), *model_keys)
  69. class RelatedField(FieldCacheMixin, Field):
  70. """Base class that all relational fields inherit from."""
  71. # Field flags
  72. one_to_many = False
  73. one_to_one = False
  74. many_to_many = False
  75. many_to_one = False
  76. @cached_property
  77. def related_model(self):
  78. # Can't cache this property until all the models are loaded.
  79. apps.check_models_ready()
  80. return self.remote_field.model
  81. def check(self, **kwargs):
  82. return [
  83. *super().check(**kwargs),
  84. *self._check_related_name_is_valid(),
  85. *self._check_related_query_name_is_valid(),
  86. *self._check_relation_model_exists(),
  87. *self._check_referencing_to_swapped_model(),
  88. *self._check_clashes(),
  89. ]
  90. def _check_related_name_is_valid(self):
  91. import keyword
  92. related_name = self.remote_field.related_name
  93. if related_name is None:
  94. return []
  95. is_valid_id = not keyword.iskeyword(related_name) and related_name.isidentifier()
  96. if not (is_valid_id or related_name.endswith('+')):
  97. return [
  98. checks.Error(
  99. "The name '%s' is invalid related_name for field %s.%s" %
  100. (self.remote_field.related_name, self.model._meta.object_name,
  101. self.name),
  102. hint="Related name must be a valid Python identifier or end with a '+'",
  103. obj=self,
  104. id='fields.E306',
  105. )
  106. ]
  107. return []
  108. def _check_related_query_name_is_valid(self):
  109. if self.remote_field.is_hidden():
  110. return []
  111. rel_query_name = self.related_query_name()
  112. errors = []
  113. if rel_query_name.endswith('_'):
  114. errors.append(
  115. checks.Error(
  116. "Reverse query name '%s' must not end with an underscore."
  117. % (rel_query_name,),
  118. hint=("Add or change a related_name or related_query_name "
  119. "argument for this field."),
  120. obj=self,
  121. id='fields.E308',
  122. )
  123. )
  124. if LOOKUP_SEP in rel_query_name:
  125. errors.append(
  126. checks.Error(
  127. "Reverse query name '%s' must not contain '%s'."
  128. % (rel_query_name, LOOKUP_SEP),
  129. hint=("Add or change a related_name or related_query_name "
  130. "argument for this field."),
  131. obj=self,
  132. id='fields.E309',
  133. )
  134. )
  135. return errors
  136. def _check_relation_model_exists(self):
  137. rel_is_missing = self.remote_field.model not in self.opts.apps.get_models()
  138. rel_is_string = isinstance(self.remote_field.model, str)
  139. model_name = self.remote_field.model if rel_is_string else self.remote_field.model._meta.object_name
  140. if rel_is_missing and (rel_is_string or not self.remote_field.model._meta.swapped):
  141. return [
  142. checks.Error(
  143. "Field defines a relation with model '%s', which is either "
  144. "not installed, or is abstract." % model_name,
  145. obj=self,
  146. id='fields.E300',
  147. )
  148. ]
  149. return []
  150. def _check_referencing_to_swapped_model(self):
  151. if (self.remote_field.model not in self.opts.apps.get_models() and
  152. not isinstance(self.remote_field.model, str) and
  153. self.remote_field.model._meta.swapped):
  154. model = "%s.%s" % (
  155. self.remote_field.model._meta.app_label,
  156. self.remote_field.model._meta.object_name
  157. )
  158. return [
  159. checks.Error(
  160. "Field defines a relation with the model '%s', which has "
  161. "been swapped out." % model,
  162. hint="Update the relation to point at 'settings.%s'." % self.remote_field.model._meta.swappable,
  163. obj=self,
  164. id='fields.E301',
  165. )
  166. ]
  167. return []
  168. def _check_clashes(self):
  169. """Check accessor and reverse query name clashes."""
  170. from django.db.models.base import ModelBase
  171. errors = []
  172. opts = self.model._meta
  173. # `f.remote_field.model` may be a string instead of a model. Skip if model name is
  174. # not resolved.
  175. if not isinstance(self.remote_field.model, ModelBase):
  176. return []
  177. # Consider that we are checking field `Model.foreign` and the models
  178. # are:
  179. #
  180. # class Target(models.Model):
  181. # model = models.IntegerField()
  182. # model_set = models.IntegerField()
  183. #
  184. # class Model(models.Model):
  185. # foreign = models.ForeignKey(Target)
  186. # m2m = models.ManyToManyField(Target)
  187. # rel_opts.object_name == "Target"
  188. rel_opts = self.remote_field.model._meta
  189. # If the field doesn't install a backward relation on the target model
  190. # (so `is_hidden` returns True), then there are no clashes to check
  191. # and we can skip these fields.
  192. rel_is_hidden = self.remote_field.is_hidden()
  193. rel_name = self.remote_field.get_accessor_name() # i. e. "model_set"
  194. rel_query_name = self.related_query_name() # i. e. "model"
  195. field_name = "%s.%s" % (opts.object_name, self.name) # i. e. "Model.field"
  196. # Check clashes between accessor or reverse query name of `field`
  197. # and any other field name -- i.e. accessor for Model.foreign is
  198. # model_set and it clashes with Target.model_set.
  199. potential_clashes = rel_opts.fields + rel_opts.many_to_many
  200. for clash_field in potential_clashes:
  201. clash_name = "%s.%s" % (rel_opts.object_name, clash_field.name) # i.e. "Target.model_set"
  202. if not rel_is_hidden and clash_field.name == rel_name:
  203. errors.append(
  204. checks.Error(
  205. "Reverse accessor for '%s' clashes with field name '%s'." % (field_name, clash_name),
  206. hint=("Rename field '%s', or add/change a related_name "
  207. "argument to the definition for field '%s'.") % (clash_name, field_name),
  208. obj=self,
  209. id='fields.E302',
  210. )
  211. )
  212. if clash_field.name == rel_query_name:
  213. errors.append(
  214. checks.Error(
  215. "Reverse query name for '%s' clashes with field name '%s'." % (field_name, clash_name),
  216. hint=("Rename field '%s', or add/change a related_name "
  217. "argument to the definition for field '%s'.") % (clash_name, field_name),
  218. obj=self,
  219. id='fields.E303',
  220. )
  221. )
  222. # Check clashes between accessors/reverse query names of `field` and
  223. # any other field accessor -- i. e. Model.foreign accessor clashes with
  224. # Model.m2m accessor.
  225. potential_clashes = (r for r in rel_opts.related_objects if r.field is not self)
  226. for clash_field in potential_clashes:
  227. clash_name = "%s.%s" % ( # i. e. "Model.m2m"
  228. clash_field.related_model._meta.object_name,
  229. clash_field.field.name)
  230. if not rel_is_hidden and clash_field.get_accessor_name() == rel_name:
  231. errors.append(
  232. checks.Error(
  233. "Reverse accessor for '%s' clashes with reverse accessor for '%s'." % (field_name, clash_name),
  234. hint=("Add or change a related_name argument "
  235. "to the definition for '%s' or '%s'.") % (field_name, clash_name),
  236. obj=self,
  237. id='fields.E304',
  238. )
  239. )
  240. if clash_field.get_accessor_name() == rel_query_name:
  241. errors.append(
  242. checks.Error(
  243. "Reverse query name for '%s' clashes with reverse query name for '%s'."
  244. % (field_name, clash_name),
  245. hint=("Add or change a related_name argument "
  246. "to the definition for '%s' or '%s'.") % (field_name, clash_name),
  247. obj=self,
  248. id='fields.E305',
  249. )
  250. )
  251. return errors
  252. def db_type(self, connection):
  253. # By default related field will not have a column as it relates to
  254. # columns from another table.
  255. return None
  256. def contribute_to_class(self, cls, name, private_only=False, **kwargs):
  257. super().contribute_to_class(cls, name, private_only=private_only, **kwargs)
  258. self.opts = cls._meta
  259. if not cls._meta.abstract:
  260. if self.remote_field.related_name:
  261. related_name = self.remote_field.related_name
  262. else:
  263. related_name = self.opts.default_related_name
  264. if related_name:
  265. related_name = related_name % {
  266. 'class': cls.__name__.lower(),
  267. 'model_name': cls._meta.model_name.lower(),
  268. 'app_label': cls._meta.app_label.lower()
  269. }
  270. self.remote_field.related_name = related_name
  271. if self.remote_field.related_query_name:
  272. related_query_name = self.remote_field.related_query_name % {
  273. 'class': cls.__name__.lower(),
  274. 'app_label': cls._meta.app_label.lower(),
  275. }
  276. self.remote_field.related_query_name = related_query_name
  277. def resolve_related_class(model, related, field):
  278. field.remote_field.model = related
  279. field.do_related_class(related, model)
  280. lazy_related_operation(resolve_related_class, cls, self.remote_field.model, field=self)
  281. def deconstruct(self):
  282. name, path, args, kwargs = super().deconstruct()
  283. if self.remote_field.limit_choices_to:
  284. kwargs['limit_choices_to'] = self.remote_field.limit_choices_to
  285. if self.remote_field.related_name is not None:
  286. kwargs['related_name'] = self.remote_field.related_name
  287. if self.remote_field.related_query_name is not None:
  288. kwargs['related_query_name'] = self.remote_field.related_query_name
  289. return name, path, args, kwargs
  290. def get_forward_related_filter(self, obj):
  291. """
  292. Return the keyword arguments that when supplied to
  293. self.model.object.filter(), would select all instances related through
  294. this field to the remote obj. This is used to build the querysets
  295. returned by related descriptors. obj is an instance of
  296. self.related_field.model.
  297. """
  298. return {
  299. '%s__%s' % (self.name, rh_field.name): getattr(obj, rh_field.attname)
  300. for _, rh_field in self.related_fields
  301. }
  302. def get_reverse_related_filter(self, obj):
  303. """
  304. Complement to get_forward_related_filter(). Return the keyword
  305. arguments that when passed to self.related_field.model.object.filter()
  306. select all instances of self.related_field.model related through
  307. this field to obj. obj is an instance of self.model.
  308. """
  309. base_filter = {
  310. rh_field.attname: getattr(obj, lh_field.attname)
  311. for lh_field, rh_field in self.related_fields
  312. }
  313. descriptor_filter = self.get_extra_descriptor_filter(obj)
  314. base_q = Q(**base_filter)
  315. if isinstance(descriptor_filter, dict):
  316. return base_q & Q(**descriptor_filter)
  317. elif descriptor_filter:
  318. return base_q & descriptor_filter
  319. return base_q
  320. @property
  321. def swappable_setting(self):
  322. """
  323. Get the setting that this is powered from for swapping, or None
  324. if it's not swapped in / marked with swappable=False.
  325. """
  326. if self.swappable:
  327. # Work out string form of "to"
  328. if isinstance(self.remote_field.model, str):
  329. to_string = self.remote_field.model
  330. else:
  331. to_string = self.remote_field.model._meta.label
  332. return apps.get_swappable_settings_name(to_string)
  333. return None
  334. def set_attributes_from_rel(self):
  335. self.name = (
  336. self.name or
  337. (self.remote_field.model._meta.model_name + '_' + self.remote_field.model._meta.pk.name)
  338. )
  339. if self.verbose_name is None:
  340. self.verbose_name = self.remote_field.model._meta.verbose_name
  341. self.remote_field.set_field_name()
  342. def do_related_class(self, other, cls):
  343. self.set_attributes_from_rel()
  344. self.contribute_to_related_class(other, self.remote_field)
  345. def get_limit_choices_to(self):
  346. """
  347. Return ``limit_choices_to`` for this model field.
  348. If it is a callable, it will be invoked and the result will be
  349. returned.
  350. """
  351. if callable(self.remote_field.limit_choices_to):
  352. return self.remote_field.limit_choices_to()
  353. return self.remote_field.limit_choices_to
  354. def formfield(self, **kwargs):
  355. """
  356. Pass ``limit_choices_to`` to the field being constructed.
  357. Only passes it if there is a type that supports related fields.
  358. This is a similar strategy used to pass the ``queryset`` to the field
  359. being constructed.
  360. """
  361. defaults = {}
  362. if hasattr(self.remote_field, 'get_related_field'):
  363. # If this is a callable, do not invoke it here. Just pass
  364. # it in the defaults for when the form class will later be
  365. # instantiated.
  366. limit_choices_to = self.remote_field.limit_choices_to
  367. defaults.update({
  368. 'limit_choices_to': limit_choices_to,
  369. })
  370. defaults.update(kwargs)
  371. return super().formfield(**defaults)
  372. def related_query_name(self):
  373. """
  374. Define the name that can be used to identify this related object in a
  375. table-spanning query.
  376. """
  377. return self.remote_field.related_query_name or self.remote_field.related_name or self.opts.model_name
  378. @property
  379. def target_field(self):
  380. """
  381. When filtering against this relation, return the field on the remote
  382. model against which the filtering should happen.
  383. """
  384. target_fields = self.get_path_info()[-1].target_fields
  385. if len(target_fields) > 1:
  386. raise exceptions.FieldError(
  387. "The relation has multiple target fields, but only single target field was asked for")
  388. return target_fields[0]
  389. def get_cache_name(self):
  390. return self.name
  391. class ForeignObject(RelatedField):
  392. """
  393. Abstraction of the ForeignKey relation to support multi-column relations.
  394. """
  395. # Field flags
  396. many_to_many = False
  397. many_to_one = True
  398. one_to_many = False
  399. one_to_one = False
  400. requires_unique_target = True
  401. related_accessor_class = ReverseManyToOneDescriptor
  402. forward_related_accessor_class = ForwardManyToOneDescriptor
  403. rel_class = ForeignObjectRel
  404. def __init__(self, to, on_delete, from_fields, to_fields, rel=None, related_name=None,
  405. related_query_name=None, limit_choices_to=None, parent_link=False,
  406. swappable=True, **kwargs):
  407. if rel is None:
  408. rel = self.rel_class(
  409. self, to,
  410. related_name=related_name,
  411. related_query_name=related_query_name,
  412. limit_choices_to=limit_choices_to,
  413. parent_link=parent_link,
  414. on_delete=on_delete,
  415. )
  416. super().__init__(rel=rel, **kwargs)
  417. self.from_fields = from_fields
  418. self.to_fields = to_fields
  419. self.swappable = swappable
  420. def check(self, **kwargs):
  421. return [
  422. *super().check(**kwargs),
  423. *self._check_to_fields_exist(),
  424. *self._check_unique_target(),
  425. ]
  426. def _check_to_fields_exist(self):
  427. # Skip nonexistent models.
  428. if isinstance(self.remote_field.model, str):
  429. return []
  430. errors = []
  431. for to_field in self.to_fields:
  432. if to_field:
  433. try:
  434. self.remote_field.model._meta.get_field(to_field)
  435. except exceptions.FieldDoesNotExist:
  436. errors.append(
  437. checks.Error(
  438. "The to_field '%s' doesn't exist on the related "
  439. "model '%s'."
  440. % (to_field, self.remote_field.model._meta.label),
  441. obj=self,
  442. id='fields.E312',
  443. )
  444. )
  445. return errors
  446. def _check_unique_target(self):
  447. rel_is_string = isinstance(self.remote_field.model, str)
  448. if rel_is_string or not self.requires_unique_target:
  449. return []
  450. try:
  451. self.foreign_related_fields
  452. except exceptions.FieldDoesNotExist:
  453. return []
  454. if not self.foreign_related_fields:
  455. return []
  456. unique_foreign_fields = {
  457. frozenset([f.name])
  458. for f in self.remote_field.model._meta.get_fields()
  459. if getattr(f, 'unique', False)
  460. }
  461. unique_foreign_fields.update({
  462. frozenset(ut)
  463. for ut in self.remote_field.model._meta.unique_together
  464. })
  465. foreign_fields = {f.name for f in self.foreign_related_fields}
  466. has_unique_constraint = any(u <= foreign_fields for u in unique_foreign_fields)
  467. if not has_unique_constraint and len(self.foreign_related_fields) > 1:
  468. field_combination = ', '.join(
  469. "'%s'" % rel_field.name for rel_field in self.foreign_related_fields
  470. )
  471. model_name = self.remote_field.model.__name__
  472. return [
  473. checks.Error(
  474. "No subset of the fields %s on model '%s' is unique."
  475. % (field_combination, model_name),
  476. hint=(
  477. "Add unique=True on any of those fields or add at "
  478. "least a subset of them to a unique_together constraint."
  479. ),
  480. obj=self,
  481. id='fields.E310',
  482. )
  483. ]
  484. elif not has_unique_constraint:
  485. field_name = self.foreign_related_fields[0].name
  486. model_name = self.remote_field.model.__name__
  487. return [
  488. checks.Error(
  489. "'%s.%s' must set unique=True because it is referenced by "
  490. "a foreign key." % (model_name, field_name),
  491. obj=self,
  492. id='fields.E311',
  493. )
  494. ]
  495. else:
  496. return []
  497. def deconstruct(self):
  498. name, path, args, kwargs = super().deconstruct()
  499. kwargs['on_delete'] = self.remote_field.on_delete
  500. kwargs['from_fields'] = self.from_fields
  501. kwargs['to_fields'] = self.to_fields
  502. if self.remote_field.parent_link:
  503. kwargs['parent_link'] = self.remote_field.parent_link
  504. # Work out string form of "to"
  505. if isinstance(self.remote_field.model, str):
  506. kwargs['to'] = self.remote_field.model
  507. else:
  508. kwargs['to'] = "%s.%s" % (
  509. self.remote_field.model._meta.app_label,
  510. self.remote_field.model._meta.object_name,
  511. )
  512. # If swappable is True, then see if we're actually pointing to the target
  513. # of a swap.
  514. swappable_setting = self.swappable_setting
  515. if swappable_setting is not None:
  516. # If it's already a settings reference, error
  517. if hasattr(kwargs['to'], "setting_name"):
  518. if kwargs['to'].setting_name != swappable_setting:
  519. raise ValueError(
  520. "Cannot deconstruct a ForeignKey pointing to a model "
  521. "that is swapped in place of more than one model (%s and %s)"
  522. % (kwargs['to'].setting_name, swappable_setting)
  523. )
  524. # Set it
  525. kwargs['to'] = SettingsReference(
  526. kwargs['to'],
  527. swappable_setting,
  528. )
  529. return name, path, args, kwargs
  530. def resolve_related_fields(self):
  531. if not self.from_fields or len(self.from_fields) != len(self.to_fields):
  532. raise ValueError('Foreign Object from and to fields must be the same non-zero length')
  533. if isinstance(self.remote_field.model, str):
  534. raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
  535. related_fields = []
  536. for index in range(len(self.from_fields)):
  537. from_field_name = self.from_fields[index]
  538. to_field_name = self.to_fields[index]
  539. from_field = (self if from_field_name == 'self'
  540. else self.opts.get_field(from_field_name))
  541. to_field = (self.remote_field.model._meta.pk if to_field_name is None
  542. else self.remote_field.model._meta.get_field(to_field_name))
  543. related_fields.append((from_field, to_field))
  544. return related_fields
  545. @property
  546. def related_fields(self):
  547. if not hasattr(self, '_related_fields'):
  548. self._related_fields = self.resolve_related_fields()
  549. return self._related_fields
  550. @property
  551. def reverse_related_fields(self):
  552. return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]
  553. @property
  554. def local_related_fields(self):
  555. return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)
  556. @property
  557. def foreign_related_fields(self):
  558. return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field)
  559. def get_local_related_value(self, instance):
  560. return self.get_instance_value_for_fields(instance, self.local_related_fields)
  561. def get_foreign_related_value(self, instance):
  562. return self.get_instance_value_for_fields(instance, self.foreign_related_fields)
  563. @staticmethod
  564. def get_instance_value_for_fields(instance, fields):
  565. ret = []
  566. opts = instance._meta
  567. for field in fields:
  568. # Gotcha: in some cases (like fixture loading) a model can have
  569. # different values in parent_ptr_id and parent's id. So, use
  570. # instance.pk (that is, parent_ptr_id) when asked for instance.id.
  571. if field.primary_key:
  572. possible_parent_link = opts.get_ancestor_link(field.model)
  573. if (not possible_parent_link or
  574. possible_parent_link.primary_key or
  575. possible_parent_link.model._meta.abstract):
  576. ret.append(instance.pk)
  577. continue
  578. ret.append(getattr(instance, field.attname))
  579. return tuple(ret)
  580. def get_attname_column(self):
  581. attname, column = super().get_attname_column()
  582. return attname, None
  583. def get_joining_columns(self, reverse_join=False):
  584. source = self.reverse_related_fields if reverse_join else self.related_fields
  585. return tuple((lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source)
  586. def get_reverse_joining_columns(self):
  587. return self.get_joining_columns(reverse_join=True)
  588. def get_extra_descriptor_filter(self, instance):
  589. """
  590. Return an extra filter condition for related object fetching when
  591. user does 'instance.fieldname', that is the extra filter is used in
  592. the descriptor of the field.
  593. The filter should be either a dict usable in .filter(**kwargs) call or
  594. a Q-object. The condition will be ANDed together with the relation's
  595. joining columns.
  596. A parallel method is get_extra_restriction() which is used in
  597. JOIN and subquery conditions.
  598. """
  599. return {}
  600. def get_extra_restriction(self, where_class, alias, related_alias):
  601. """
  602. Return a pair condition used for joining and subquery pushdown. The
  603. condition is something that responds to as_sql(compiler, connection)
  604. method.
  605. Note that currently referring both the 'alias' and 'related_alias'
  606. will not work in some conditions, like subquery pushdown.
  607. A parallel method is get_extra_descriptor_filter() which is used in
  608. instance.fieldname related object fetching.
  609. """
  610. return None
  611. def get_path_info(self, filtered_relation=None):
  612. """Get path from this field to the related model."""
  613. opts = self.remote_field.model._meta
  614. from_opts = self.model._meta
  615. return [PathInfo(
  616. from_opts=from_opts,
  617. to_opts=opts,
  618. target_fields=self.foreign_related_fields,
  619. join_field=self,
  620. m2m=False,
  621. direct=True,
  622. filtered_relation=filtered_relation,
  623. )]
  624. def get_reverse_path_info(self, filtered_relation=None):
  625. """Get path from the related model to this field's model."""
  626. opts = self.model._meta
  627. from_opts = self.remote_field.model._meta
  628. return [PathInfo(
  629. from_opts=from_opts,
  630. to_opts=opts,
  631. target_fields=(opts.pk,),
  632. join_field=self.remote_field,
  633. m2m=not self.unique,
  634. direct=False,
  635. filtered_relation=filtered_relation,
  636. )]
  637. @classmethod
  638. @functools.lru_cache(maxsize=None)
  639. def get_lookups(cls):
  640. bases = inspect.getmro(cls)
  641. bases = bases[:bases.index(ForeignObject) + 1]
  642. class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in bases]
  643. return cls.merge_dicts(class_lookups)
  644. def contribute_to_class(self, cls, name, private_only=False, **kwargs):
  645. super().contribute_to_class(cls, name, private_only=private_only, **kwargs)
  646. setattr(cls, self.name, self.forward_related_accessor_class(self))
  647. def contribute_to_related_class(self, cls, related):
  648. # Internal FK's - i.e., those with a related name ending with '+' -
  649. # and swapped models don't get a related descriptor.
  650. if not self.remote_field.is_hidden() and not related.related_model._meta.swapped:
  651. setattr(cls._meta.concrete_model, related.get_accessor_name(), self.related_accessor_class(related))
  652. # While 'limit_choices_to' might be a callable, simply pass
  653. # it along for later - this is too early because it's still
  654. # model load time.
  655. if self.remote_field.limit_choices_to:
  656. cls._meta.related_fkey_lookups.append(self.remote_field.limit_choices_to)
  657. ForeignObject.register_lookup(RelatedIn)
  658. ForeignObject.register_lookup(RelatedExact)
  659. ForeignObject.register_lookup(RelatedLessThan)
  660. ForeignObject.register_lookup(RelatedGreaterThan)
  661. ForeignObject.register_lookup(RelatedGreaterThanOrEqual)
  662. ForeignObject.register_lookup(RelatedLessThanOrEqual)
  663. ForeignObject.register_lookup(RelatedIsNull)
  664. class ForeignKey(ForeignObject):
  665. """
  666. Provide a many-to-one relation by adding a column to the local model
  667. to hold the remote value.
  668. By default ForeignKey will target the pk of the remote model but this
  669. behavior can be changed by using the ``to_field`` argument.
  670. """
  671. # Field flags
  672. many_to_many = False
  673. many_to_one = True
  674. one_to_many = False
  675. one_to_one = False
  676. rel_class = ManyToOneRel
  677. empty_strings_allowed = False
  678. default_error_messages = {
  679. 'invalid': _('%(model)s instance with %(field)s %(value)r does not exist.')
  680. }
  681. description = _("Foreign Key (type determined by related field)")
  682. def __init__(self, to, on_delete, related_name=None, related_query_name=None,
  683. limit_choices_to=None, parent_link=False, to_field=None,
  684. db_constraint=True, **kwargs):
  685. try:
  686. to._meta.model_name
  687. except AttributeError:
  688. assert isinstance(to, str), (
  689. "%s(%r) is invalid. First parameter to ForeignKey must be "
  690. "either a model, a model name, or the string %r" % (
  691. self.__class__.__name__, to,
  692. RECURSIVE_RELATIONSHIP_CONSTANT,
  693. )
  694. )
  695. else:
  696. # For backwards compatibility purposes, we need to *try* and set
  697. # the to_field during FK construction. It won't be guaranteed to
  698. # be correct until contribute_to_class is called. Refs #12190.
  699. to_field = to_field or (to._meta.pk and to._meta.pk.name)
  700. kwargs['rel'] = self.rel_class(
  701. self, to, to_field,
  702. related_name=related_name,
  703. related_query_name=related_query_name,
  704. limit_choices_to=limit_choices_to,
  705. parent_link=parent_link,
  706. on_delete=on_delete,
  707. )
  708. kwargs.setdefault('db_index', True)
  709. super().__init__(to, on_delete, from_fields=['self'], to_fields=[to_field], **kwargs)
  710. self.db_constraint = db_constraint
  711. def check(self, **kwargs):
  712. return [
  713. *super().check(**kwargs),
  714. *self._check_on_delete(),
  715. *self._check_unique(),
  716. ]
  717. def _check_on_delete(self):
  718. on_delete = getattr(self.remote_field, 'on_delete', None)
  719. if on_delete == SET_NULL and not self.null:
  720. return [
  721. checks.Error(
  722. 'Field specifies on_delete=SET_NULL, but cannot be null.',
  723. hint='Set null=True argument on the field, or change the on_delete rule.',
  724. obj=self,
  725. id='fields.E320',
  726. )
  727. ]
  728. elif on_delete == SET_DEFAULT and not self.has_default():
  729. return [
  730. checks.Error(
  731. 'Field specifies on_delete=SET_DEFAULT, but has no default value.',
  732. hint='Set a default value, or change the on_delete rule.',
  733. obj=self,
  734. id='fields.E321',
  735. )
  736. ]
  737. else:
  738. return []
  739. def _check_unique(self, **kwargs):
  740. return [
  741. checks.Warning(
  742. 'Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.',
  743. hint='ForeignKey(unique=True) is usually better served by a OneToOneField.',
  744. obj=self,
  745. id='fields.W342',
  746. )
  747. ] if self.unique else []
  748. def deconstruct(self):
  749. name, path, args, kwargs = super().deconstruct()
  750. del kwargs['to_fields']
  751. del kwargs['from_fields']
  752. # Handle the simpler arguments
  753. if self.db_index:
  754. del kwargs['db_index']
  755. else:
  756. kwargs['db_index'] = False
  757. if self.db_constraint is not True:
  758. kwargs['db_constraint'] = self.db_constraint
  759. # Rel needs more work.
  760. to_meta = getattr(self.remote_field.model, "_meta", None)
  761. if self.remote_field.field_name and (
  762. not to_meta or (to_meta.pk and self.remote_field.field_name != to_meta.pk.name)):
  763. kwargs['to_field'] = self.remote_field.field_name
  764. return name, path, args, kwargs
  765. def to_python(self, value):
  766. return self.target_field.to_python(value)
  767. @property
  768. def target_field(self):
  769. return self.foreign_related_fields[0]
  770. def get_reverse_path_info(self, filtered_relation=None):
  771. """Get path from the related model to this field's model."""
  772. opts = self.model._meta
  773. from_opts = self.remote_field.model._meta
  774. return [PathInfo(
  775. from_opts=from_opts,
  776. to_opts=opts,
  777. target_fields=(opts.pk,),
  778. join_field=self.remote_field,
  779. m2m=not self.unique,
  780. direct=False,
  781. filtered_relation=filtered_relation,
  782. )]
  783. def validate(self, value, model_instance):
  784. if self.remote_field.parent_link:
  785. return
  786. super().validate(value, model_instance)
  787. if value is None:
  788. return
  789. using = router.db_for_read(self.remote_field.model, instance=model_instance)
  790. qs = self.remote_field.model._default_manager.using(using).filter(
  791. **{self.remote_field.field_name: value}
  792. )
  793. qs = qs.complex_filter(self.get_limit_choices_to())
  794. if not qs.exists():
  795. raise exceptions.ValidationError(
  796. self.error_messages['invalid'],
  797. code='invalid',
  798. params={
  799. 'model': self.remote_field.model._meta.verbose_name, 'pk': value,
  800. 'field': self.remote_field.field_name, 'value': value,
  801. }, # 'pk' is included for backwards compatibility
  802. )
  803. def get_attname(self):
  804. return '%s_id' % self.name
  805. def get_attname_column(self):
  806. attname = self.get_attname()
  807. column = self.db_column or attname
  808. return attname, column
  809. def get_default(self):
  810. """Return the to_field if the default value is an object."""
  811. field_default = super().get_default()
  812. if isinstance(field_default, self.remote_field.model):
  813. return getattr(field_default, self.target_field.attname)
  814. return field_default
  815. def get_db_prep_save(self, value, connection):
  816. if value is None or (value == '' and
  817. (not self.target_field.empty_strings_allowed or
  818. connection.features.interprets_empty_strings_as_nulls)):
  819. return None
  820. else:
  821. return self.target_field.get_db_prep_save(value, connection=connection)
  822. def get_db_prep_value(self, value, connection, prepared=False):
  823. return self.target_field.get_db_prep_value(value, connection, prepared)
  824. def contribute_to_related_class(self, cls, related):
  825. super().contribute_to_related_class(cls, related)
  826. if self.remote_field.field_name is None:
  827. self.remote_field.field_name = cls._meta.pk.name
  828. def formfield(self, *, using=None, **kwargs):
  829. if isinstance(self.remote_field.model, str):
  830. raise ValueError("Cannot create form field for %r yet, because "
  831. "its related model %r has not been loaded yet" %
  832. (self.name, self.remote_field.model))
  833. return super().formfield(**{
  834. 'form_class': forms.ModelChoiceField,
  835. 'queryset': self.remote_field.model._default_manager.using(using),
  836. 'to_field_name': self.remote_field.field_name,
  837. **kwargs,
  838. })
  839. def db_check(self, connection):
  840. return []
  841. def db_type(self, connection):
  842. return self.target_field.rel_db_type(connection=connection)
  843. def db_parameters(self, connection):
  844. return {"type": self.db_type(connection), "check": self.db_check(connection)}
  845. def convert_empty_strings(self, value, expression, connection):
  846. if (not value) and isinstance(value, str):
  847. return None
  848. return value
  849. def get_db_converters(self, connection):
  850. converters = super().get_db_converters(connection)
  851. if connection.features.interprets_empty_strings_as_nulls:
  852. converters += [self.convert_empty_strings]
  853. return converters
  854. def get_col(self, alias, output_field=None):
  855. if output_field is None:
  856. output_field = self.target_field
  857. while isinstance(output_field, ForeignKey):
  858. output_field = output_field.target_field
  859. if output_field is self:
  860. raise ValueError('Cannot resolve output_field.')
  861. return super().get_col(alias, output_field)
  862. class OneToOneField(ForeignKey):
  863. """
  864. A OneToOneField is essentially the same as a ForeignKey, with the exception
  865. that it always carries a "unique" constraint with it and the reverse
  866. relation always returns the object pointed to (since there will only ever
  867. be one), rather than returning a list.
  868. """
  869. # Field flags
  870. many_to_many = False
  871. many_to_one = False
  872. one_to_many = False
  873. one_to_one = True
  874. related_accessor_class = ReverseOneToOneDescriptor
  875. forward_related_accessor_class = ForwardOneToOneDescriptor
  876. rel_class = OneToOneRel
  877. description = _("One-to-one relationship")
  878. def __init__(self, to, on_delete, to_field=None, **kwargs):
  879. kwargs['unique'] = True
  880. super().__init__(to, on_delete, to_field=to_field, **kwargs)
  881. def deconstruct(self):
  882. name, path, args, kwargs = super().deconstruct()
  883. if "unique" in kwargs:
  884. del kwargs['unique']
  885. return name, path, args, kwargs
  886. def formfield(self, **kwargs):
  887. if self.remote_field.parent_link:
  888. return None
  889. return super().formfield(**kwargs)
  890. def save_form_data(self, instance, data):
  891. if isinstance(data, self.remote_field.model):
  892. setattr(instance, self.name, data)
  893. else:
  894. setattr(instance, self.attname, data)
  895. def _check_unique(self, **kwargs):
  896. # Override ForeignKey since check isn't applicable here.
  897. return []
  898. def create_many_to_many_intermediary_model(field, klass):
  899. from django.db import models
  900. def set_managed(model, related, through):
  901. through._meta.managed = model._meta.managed or related._meta.managed
  902. to_model = resolve_relation(klass, field.remote_field.model)
  903. name = '%s_%s' % (klass._meta.object_name, field.name)
  904. lazy_related_operation(set_managed, klass, to_model, name)
  905. to = make_model_tuple(to_model)[1]
  906. from_ = klass._meta.model_name
  907. if to == from_:
  908. to = 'to_%s' % to
  909. from_ = 'from_%s' % from_
  910. meta = type('Meta', (), {
  911. 'db_table': field._get_m2m_db_table(klass._meta),
  912. 'auto_created': klass,
  913. 'app_label': klass._meta.app_label,
  914. 'db_tablespace': klass._meta.db_tablespace,
  915. 'unique_together': (from_, to),
  916. 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to},
  917. 'verbose_name_plural': _('%(from)s-%(to)s relationships') % {'from': from_, 'to': to},
  918. 'apps': field.model._meta.apps,
  919. })
  920. # Construct and return the new class.
  921. return type(name, (models.Model,), {
  922. 'Meta': meta,
  923. '__module__': klass.__module__,
  924. from_: models.ForeignKey(
  925. klass,
  926. related_name='%s+' % name,
  927. db_tablespace=field.db_tablespace,
  928. db_constraint=field.remote_field.db_constraint,
  929. on_delete=CASCADE,
  930. ),
  931. to: models.ForeignKey(
  932. to_model,
  933. related_name='%s+' % name,
  934. db_tablespace=field.db_tablespace,
  935. db_constraint=field.remote_field.db_constraint,
  936. on_delete=CASCADE,
  937. )
  938. })
  939. class ManyToManyField(RelatedField):
  940. """
  941. Provide a many-to-many relation by using an intermediary model that
  942. holds two ForeignKey fields pointed at the two sides of the relation.
  943. Unless a ``through`` model was provided, ManyToManyField will use the
  944. create_many_to_many_intermediary_model factory to automatically generate
  945. the intermediary model.
  946. """
  947. # Field flags
  948. many_to_many = True
  949. many_to_one = False
  950. one_to_many = False
  951. one_to_one = False
  952. rel_class = ManyToManyRel
  953. description = _("Many-to-many relationship")
  954. def __init__(self, to, related_name=None, related_query_name=None,
  955. limit_choices_to=None, symmetrical=None, through=None,
  956. through_fields=None, db_constraint=True, db_table=None,
  957. swappable=True, **kwargs):
  958. try:
  959. to._meta
  960. except AttributeError:
  961. assert isinstance(to, str), (
  962. "%s(%r) is invalid. First parameter to ManyToManyField must be "
  963. "either a model, a model name, or the string %r" %
  964. (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
  965. )
  966. if symmetrical is None:
  967. symmetrical = (to == RECURSIVE_RELATIONSHIP_CONSTANT)
  968. if through is not None:
  969. assert db_table is None, (
  970. "Cannot specify a db_table if an intermediary model is used."
  971. )
  972. kwargs['rel'] = self.rel_class(
  973. self, to,
  974. related_name=related_name,
  975. related_query_name=related_query_name,
  976. limit_choices_to=limit_choices_to,
  977. symmetrical=symmetrical,
  978. through=through,
  979. through_fields=through_fields,
  980. db_constraint=db_constraint,
  981. )
  982. self.has_null_arg = 'null' in kwargs
  983. super().__init__(**kwargs)
  984. self.db_table = db_table
  985. self.swappable = swappable
  986. def check(self, **kwargs):
  987. return [
  988. *super().check(**kwargs),
  989. *self._check_unique(**kwargs),
  990. *self._check_relationship_model(**kwargs),
  991. *self._check_ignored_options(**kwargs),
  992. *self._check_table_uniqueness(**kwargs),
  993. ]
  994. def _check_unique(self, **kwargs):
  995. if self.unique:
  996. return [
  997. checks.Error(
  998. 'ManyToManyFields cannot be unique.',
  999. obj=self,
  1000. id='fields.E330',
  1001. )
  1002. ]
  1003. return []
  1004. def _check_ignored_options(self, **kwargs):
  1005. warnings = []
  1006. if self.has_null_arg:
  1007. warnings.append(
  1008. checks.Warning(
  1009. 'null has no effect on ManyToManyField.',
  1010. obj=self,
  1011. id='fields.W340',
  1012. )
  1013. )
  1014. if self._validators:
  1015. warnings.append(
  1016. checks.Warning(
  1017. 'ManyToManyField does not support validators.',
  1018. obj=self,
  1019. id='fields.W341',
  1020. )
  1021. )
  1022. if (self.remote_field.limit_choices_to and self.remote_field.through and
  1023. not self.remote_field.through._meta.auto_created):
  1024. warnings.append(
  1025. checks.Warning(
  1026. 'limit_choices_to has no effect on ManyToManyField '
  1027. 'with a through model.',
  1028. obj=self,
  1029. id='fields.W343',
  1030. )
  1031. )
  1032. return warnings
  1033. def _check_relationship_model(self, from_model=None, **kwargs):
  1034. if hasattr(self.remote_field.through, '_meta'):
  1035. qualified_model_name = "%s.%s" % (
  1036. self.remote_field.through._meta.app_label, self.remote_field.through.__name__)
  1037. else:
  1038. qualified_model_name = self.remote_field.through
  1039. errors = []
  1040. if self.remote_field.through not in self.opts.apps.get_models(include_auto_created=True):
  1041. # The relationship model is not installed.
  1042. errors.append(
  1043. checks.Error(
  1044. "Field specifies a many-to-many relation through model "
  1045. "'%s', which has not been installed." % qualified_model_name,
  1046. obj=self,
  1047. id='fields.E331',
  1048. )
  1049. )
  1050. else:
  1051. assert from_model is not None, (
  1052. "ManyToManyField with intermediate "
  1053. "tables cannot be checked if you don't pass the model "
  1054. "where the field is attached to."
  1055. )
  1056. # Set some useful local variables
  1057. to_model = resolve_relation(from_model, self.remote_field.model)
  1058. from_model_name = from_model._meta.object_name
  1059. if isinstance(to_model, str):
  1060. to_model_name = to_model
  1061. else:
  1062. to_model_name = to_model._meta.object_name
  1063. relationship_model_name = self.remote_field.through._meta.object_name
  1064. self_referential = from_model == to_model
  1065. # Check symmetrical attribute.
  1066. if (self_referential and self.remote_field.symmetrical and
  1067. not self.remote_field.through._meta.auto_created):
  1068. errors.append(
  1069. checks.Error(
  1070. 'Many-to-many fields with intermediate tables must not be symmetrical.',
  1071. obj=self,
  1072. id='fields.E332',
  1073. )
  1074. )
  1075. # Count foreign keys in intermediate model
  1076. if self_referential:
  1077. seen_self = sum(
  1078. from_model == getattr(field.remote_field, 'model', None)
  1079. for field in self.remote_field.through._meta.fields
  1080. )
  1081. if seen_self > 2 and not self.remote_field.through_fields:
  1082. errors.append(
  1083. checks.Error(
  1084. "The model is used as an intermediate model by "
  1085. "'%s', but it has more than two foreign keys "
  1086. "to '%s', which is ambiguous. You must specify "
  1087. "which two foreign keys Django should use via the "
  1088. "through_fields keyword argument." % (self, from_model_name),
  1089. hint="Use through_fields to specify which two foreign keys Django should use.",
  1090. obj=self.remote_field.through,
  1091. id='fields.E333',
  1092. )
  1093. )
  1094. else:
  1095. # Count foreign keys in relationship model
  1096. seen_from = sum(
  1097. from_model == getattr(field.remote_field, 'model', None)
  1098. for field in self.remote_field.through._meta.fields
  1099. )
  1100. seen_to = sum(
  1101. to_model == getattr(field.remote_field, 'model', None)
  1102. for field in self.remote_field.through._meta.fields
  1103. )
  1104. if seen_from > 1 and not self.remote_field.through_fields:
  1105. errors.append(
  1106. checks.Error(
  1107. ("The model is used as an intermediate model by "
  1108. "'%s', but it has more than one foreign key "
  1109. "from '%s', which is ambiguous. You must specify "
  1110. "which foreign key Django should use via the "
  1111. "through_fields keyword argument.") % (self, from_model_name),
  1112. hint=(
  1113. 'If you want to create a recursive relationship, '
  1114. 'use ForeignKey("self", symmetrical=False, through="%s").'
  1115. ) % relationship_model_name,
  1116. obj=self,
  1117. id='fields.E334',
  1118. )
  1119. )
  1120. if seen_to > 1 and not self.remote_field.through_fields:
  1121. errors.append(
  1122. checks.Error(
  1123. "The model is used as an intermediate model by "
  1124. "'%s', but it has more than one foreign key "
  1125. "to '%s', which is ambiguous. You must specify "
  1126. "which foreign key Django should use via the "
  1127. "through_fields keyword argument." % (self, to_model_name),
  1128. hint=(
  1129. 'If you want to create a recursive relationship, '
  1130. 'use ForeignKey("self", symmetrical=False, through="%s").'
  1131. ) % relationship_model_name,
  1132. obj=self,
  1133. id='fields.E335',
  1134. )
  1135. )
  1136. if seen_from == 0 or seen_to == 0:
  1137. errors.append(
  1138. checks.Error(
  1139. "The model is used as an intermediate model by "
  1140. "'%s', but it does not have a foreign key to '%s' or '%s'." % (
  1141. self, from_model_name, to_model_name
  1142. ),
  1143. obj=self.remote_field.through,
  1144. id='fields.E336',
  1145. )
  1146. )
  1147. # Validate `through_fields`.
  1148. if self.remote_field.through_fields is not None:
  1149. # Validate that we're given an iterable of at least two items
  1150. # and that none of them is "falsy".
  1151. if not (len(self.remote_field.through_fields) >= 2 and
  1152. self.remote_field.through_fields[0] and self.remote_field.through_fields[1]):
  1153. errors.append(
  1154. checks.Error(
  1155. "Field specifies 'through_fields' but does not provide "
  1156. "the names of the two link fields that should be used "
  1157. "for the relation through model '%s'." % qualified_model_name,
  1158. hint="Make sure you specify 'through_fields' as through_fields=('field1', 'field2')",
  1159. obj=self,
  1160. id='fields.E337',
  1161. )
  1162. )
  1163. # Validate the given through fields -- they should be actual
  1164. # fields on the through model, and also be foreign keys to the
  1165. # expected models.
  1166. else:
  1167. assert from_model is not None, (
  1168. "ManyToManyField with intermediate "
  1169. "tables cannot be checked if you don't pass the model "
  1170. "where the field is attached to."
  1171. )
  1172. source, through, target = from_model, self.remote_field.through, self.remote_field.model
  1173. source_field_name, target_field_name = self.remote_field.through_fields[:2]
  1174. for field_name, related_model in ((source_field_name, source),
  1175. (target_field_name, target)):
  1176. possible_field_names = []
  1177. for f in through._meta.fields:
  1178. if hasattr(f, 'remote_field') and getattr(f.remote_field, 'model', None) == related_model:
  1179. possible_field_names.append(f.name)
  1180. if possible_field_names:
  1181. hint = "Did you mean one of the following foreign keys to '%s': %s?" % (
  1182. related_model._meta.object_name,
  1183. ', '.join(possible_field_names),
  1184. )
  1185. else:
  1186. hint = None
  1187. try:
  1188. field = through._meta.get_field(field_name)
  1189. except exceptions.FieldDoesNotExist:
  1190. errors.append(
  1191. checks.Error(
  1192. "The intermediary model '%s' has no field '%s'."
  1193. % (qualified_model_name, field_name),
  1194. hint=hint,
  1195. obj=self,
  1196. id='fields.E338',
  1197. )
  1198. )
  1199. else:
  1200. if not (hasattr(field, 'remote_field') and
  1201. getattr(field.remote_field, 'model', None) == related_model):
  1202. errors.append(
  1203. checks.Error(
  1204. "'%s.%s' is not a foreign key to '%s'." % (
  1205. through._meta.object_name, field_name,
  1206. related_model._meta.object_name,
  1207. ),
  1208. hint=hint,
  1209. obj=self,
  1210. id='fields.E339',
  1211. )
  1212. )
  1213. return errors
  1214. def _check_table_uniqueness(self, **kwargs):
  1215. if isinstance(self.remote_field.through, str) or not self.remote_field.through._meta.managed:
  1216. return []
  1217. registered_tables = {
  1218. model._meta.db_table: model
  1219. for model in self.opts.apps.get_models(include_auto_created=True)
  1220. if model != self.remote_field.through and model._meta.managed
  1221. }
  1222. m2m_db_table = self.m2m_db_table()
  1223. model = registered_tables.get(m2m_db_table)
  1224. # The second condition allows multiple m2m relations on a model if
  1225. # some point to a through model that proxies another through model.
  1226. if model and model._meta.concrete_model != self.remote_field.through._meta.concrete_model:
  1227. if model._meta.auto_created:
  1228. def _get_field_name(model):
  1229. for field in model._meta.auto_created._meta.many_to_many:
  1230. if field.remote_field.through is model:
  1231. return field.name
  1232. opts = model._meta.auto_created._meta
  1233. clashing_obj = '%s.%s' % (opts.label, _get_field_name(model))
  1234. else:
  1235. clashing_obj = model._meta.label
  1236. return [
  1237. checks.Error(
  1238. "The field's intermediary table '%s' clashes with the "
  1239. "table name of '%s'." % (m2m_db_table, clashing_obj),
  1240. obj=self,
  1241. id='fields.E340',
  1242. )
  1243. ]
  1244. return []
  1245. def deconstruct(self):
  1246. name, path, args, kwargs = super().deconstruct()
  1247. # Handle the simpler arguments.
  1248. if self.db_table is not None:
  1249. kwargs['db_table'] = self.db_table
  1250. if self.remote_field.db_constraint is not True:
  1251. kwargs['db_constraint'] = self.remote_field.db_constraint
  1252. # Rel needs more work.
  1253. if isinstance(self.remote_field.model, str):
  1254. kwargs['to'] = self.remote_field.model
  1255. else:
  1256. kwargs['to'] = "%s.%s" % (
  1257. self.remote_field.model._meta.app_label,
  1258. self.remote_field.model._meta.object_name,
  1259. )
  1260. if getattr(self.remote_field, 'through', None) is not None:
  1261. if isinstance(self.remote_field.through, str):
  1262. kwargs['through'] = self.remote_field.through
  1263. elif not self.remote_field.through._meta.auto_created:
  1264. kwargs['through'] = "%s.%s" % (
  1265. self.remote_field.through._meta.app_label,
  1266. self.remote_field.through._meta.object_name,
  1267. )
  1268. # If swappable is True, then see if we're actually pointing to the target
  1269. # of a swap.
  1270. swappable_setting = self.swappable_setting
  1271. if swappable_setting is not None:
  1272. # If it's already a settings reference, error.
  1273. if hasattr(kwargs['to'], "setting_name"):
  1274. if kwargs['to'].setting_name != swappable_setting:
  1275. raise ValueError(
  1276. "Cannot deconstruct a ManyToManyField pointing to a "
  1277. "model that is swapped in place of more than one model "
  1278. "(%s and %s)" % (kwargs['to'].setting_name, swappable_setting)
  1279. )
  1280. kwargs['to'] = SettingsReference(
  1281. kwargs['to'],
  1282. swappable_setting,
  1283. )
  1284. return name, path, args, kwargs
  1285. def _get_path_info(self, direct=False, filtered_relation=None):
  1286. """Called by both direct and indirect m2m traversal."""
  1287. int_model = self.remote_field.through
  1288. linkfield1 = int_model._meta.get_field(self.m2m_field_name())
  1289. linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name())
  1290. if direct:
  1291. join1infos = linkfield1.get_reverse_path_info()
  1292. join2infos = linkfield2.get_path_info(filtered_relation)
  1293. else:
  1294. join1infos = linkfield2.get_reverse_path_info()
  1295. join2infos = linkfield1.get_path_info(filtered_relation)
  1296. # Get join infos between the last model of join 1 and the first model
  1297. # of join 2. Assume the only reason these may differ is due to model
  1298. # inheritance.
  1299. join1_final = join1infos[-1].to_opts
  1300. join2_initial = join2infos[0].from_opts
  1301. if join1_final is join2_initial:
  1302. intermediate_infos = []
  1303. elif issubclass(join1_final.model, join2_initial.model):
  1304. intermediate_infos = join1_final.get_path_to_parent(join2_initial.model)
  1305. else:
  1306. intermediate_infos = join2_initial.get_path_from_parent(join1_final.model)
  1307. return [*join1infos, *intermediate_infos, *join2infos]
  1308. def get_path_info(self, filtered_relation=None):
  1309. return self._get_path_info(direct=True, filtered_relation=filtered_relation)
  1310. def get_reverse_path_info(self, filtered_relation=None):
  1311. return self._get_path_info(direct=False, filtered_relation=filtered_relation)
  1312. def _get_m2m_db_table(self, opts):
  1313. """
  1314. Function that can be curried to provide the m2m table name for this
  1315. relation.
  1316. """
  1317. if self.remote_field.through is not None:
  1318. return self.remote_field.through._meta.db_table
  1319. elif self.db_table:
  1320. return self.db_table
  1321. else:
  1322. m2m_table_name = '%s_%s' % (utils.strip_quotes(opts.db_table), self.name)
  1323. return utils.truncate_name(m2m_table_name, connection.ops.max_name_length())
  1324. def _get_m2m_attr(self, related, attr):
  1325. """
  1326. Function that can be curried to provide the source accessor or DB
  1327. column name for the m2m table.
  1328. """
  1329. cache_attr = '_m2m_%s_cache' % attr
  1330. if hasattr(self, cache_attr):
  1331. return getattr(self, cache_attr)
  1332. if self.remote_field.through_fields is not None:
  1333. link_field_name = self.remote_field.through_fields[0]
  1334. else:
  1335. link_field_name = None
  1336. for f in self.remote_field.through._meta.fields:
  1337. if (f.is_relation and f.remote_field.model == related.related_model and
  1338. (link_field_name is None or link_field_name == f.name)):
  1339. setattr(self, cache_attr, getattr(f, attr))
  1340. return getattr(self, cache_attr)
  1341. def _get_m2m_reverse_attr(self, related, attr):
  1342. """
  1343. Function that can be curried to provide the related accessor or DB
  1344. column name for the m2m table.
  1345. """
  1346. cache_attr = '_m2m_reverse_%s_cache' % attr
  1347. if hasattr(self, cache_attr):
  1348. return getattr(self, cache_attr)
  1349. found = False
  1350. if self.remote_field.through_fields is not None:
  1351. link_field_name = self.remote_field.through_fields[1]
  1352. else:
  1353. link_field_name = None
  1354. for f in self.remote_field.through._meta.fields:
  1355. if f.is_relation and f.remote_field.model == related.model:
  1356. if link_field_name is None and related.related_model == related.model:
  1357. # If this is an m2m-intermediate to self,
  1358. # the first foreign key you find will be
  1359. # the source column. Keep searching for
  1360. # the second foreign key.
  1361. if found:
  1362. setattr(self, cache_attr, getattr(f, attr))
  1363. break
  1364. else:
  1365. found = True
  1366. elif link_field_name is None or link_field_name == f.name:
  1367. setattr(self, cache_attr, getattr(f, attr))
  1368. break
  1369. return getattr(self, cache_attr)
  1370. def contribute_to_class(self, cls, name, **kwargs):
  1371. # To support multiple relations to self, it's useful to have a non-None
  1372. # related name on symmetrical relations for internal reasons. The
  1373. # concept doesn't make a lot of sense externally ("you want me to
  1374. # specify *what* on my non-reversible relation?!"), so we set it up
  1375. # automatically. The funky name reduces the chance of an accidental
  1376. # clash.
  1377. if self.remote_field.symmetrical and (
  1378. self.remote_field.model == "self" or self.remote_field.model == cls._meta.object_name):
  1379. self.remote_field.related_name = "%s_rel_+" % name
  1380. elif self.remote_field.is_hidden():
  1381. # If the backwards relation is disabled, replace the original
  1382. # related_name with one generated from the m2m field name. Django
  1383. # still uses backwards relations internally and we need to avoid
  1384. # clashes between multiple m2m fields with related_name == '+'.
  1385. self.remote_field.related_name = "_%s_%s_+" % (cls.__name__.lower(), name)
  1386. super().contribute_to_class(cls, name, **kwargs)
  1387. # The intermediate m2m model is not auto created if:
  1388. # 1) There is a manually specified intermediate, or
  1389. # 2) The class owning the m2m field is abstract.
  1390. # 3) The class owning the m2m field has been swapped out.
  1391. if not cls._meta.abstract:
  1392. if self.remote_field.through:
  1393. def resolve_through_model(_, model, field):
  1394. field.remote_field.through = model
  1395. lazy_related_operation(resolve_through_model, cls, self.remote_field.through, field=self)
  1396. elif not cls._meta.swapped:
  1397. self.remote_field.through = create_many_to_many_intermediary_model(self, cls)
  1398. # Add the descriptor for the m2m relation.
  1399. setattr(cls, self.name, ManyToManyDescriptor(self.remote_field, reverse=False))
  1400. # Set up the accessor for the m2m table name for the relation.
  1401. self.m2m_db_table = partial(self._get_m2m_db_table, cls._meta)
  1402. def contribute_to_related_class(self, cls, related):
  1403. # Internal M2Ms (i.e., those with a related name ending with '+')
  1404. # and swapped models don't get a related descriptor.
  1405. if not self.remote_field.is_hidden() and not related.related_model._meta.swapped:
  1406. setattr(cls, related.get_accessor_name(), ManyToManyDescriptor(self.remote_field, reverse=True))
  1407. # Set up the accessors for the column names on the m2m table.
  1408. self.m2m_column_name = partial(self._get_m2m_attr, related, 'column')
  1409. self.m2m_reverse_name = partial(self._get_m2m_reverse_attr, related, 'column')
  1410. self.m2m_field_name = partial(self._get_m2m_attr, related, 'name')
  1411. self.m2m_reverse_field_name = partial(self._get_m2m_reverse_attr, related, 'name')
  1412. get_m2m_rel = partial(self._get_m2m_attr, related, 'remote_field')
  1413. self.m2m_target_field_name = lambda: get_m2m_rel().field_name
  1414. get_m2m_reverse_rel = partial(self._get_m2m_reverse_attr, related, 'remote_field')
  1415. self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name
  1416. def set_attributes_from_rel(self):
  1417. pass
  1418. def value_from_object(self, obj):
  1419. return [] if obj.pk is None else list(getattr(obj, self.attname).all())
  1420. def save_form_data(self, instance, data):
  1421. getattr(instance, self.attname).set(data)
  1422. def formfield(self, *, using=None, **kwargs):
  1423. defaults = {
  1424. 'form_class': forms.ModelMultipleChoiceField,
  1425. 'queryset': self.remote_field.model._default_manager.using(using),
  1426. **kwargs,
  1427. }
  1428. # If initial is passed in, it's a list of related objects, but the
  1429. # MultipleChoiceField takes a list of IDs.
  1430. if defaults.get('initial') is not None:
  1431. initial = defaults['initial']
  1432. if callable(initial):
  1433. initial = initial()
  1434. defaults['initial'] = [i.pk for i in initial]
  1435. return super().formfield(**defaults)
  1436. def db_check(self, connection):
  1437. return None
  1438. def db_type(self, connection):
  1439. # A ManyToManyField is not represented by a single column,
  1440. # so return None.
  1441. return None
  1442. def db_parameters(self, connection):
  1443. return {"type": None, "check": None}