related.py 77 KB

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