Development of an internal social media platform with personalised dashboards for students
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 66KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  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.core import checks, exceptions
  7. from django.db import connection, router
  8. from django.db.backends import utils
  9. from django.db.models import Q
  10. from django.db.models.constants import LOOKUP_SEP
  11. from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
  12. from django.db.models.query_utils import PathInfo
  13. from django.db.models.utils import make_model_tuple
  14. from django.utils.functional import cached_property
  15. from django.utils.translation import gettext_lazy as _
  16. from . import Field
  17. from .mixins import FieldCacheMixin
  18. from .related_descriptors import (
  19. ForwardManyToOneDescriptor, ForwardOneToOneDescriptor,
  20. ManyToManyDescriptor, ReverseManyToOneDescriptor,
  21. ReverseOneToOneDescriptor,
  22. )
  23. from .related_lookups import (
  24. RelatedExact, RelatedGreaterThan, RelatedGreaterThanOrEqual, RelatedIn,
  25. RelatedIsNull, RelatedLessThan, RelatedLessThanOrEqual,
  26. )
  27. from .reverse_related import (
  28. ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel,
  29. )
  30. RECURSIVE_RELATIONSHIP_CONSTANT = 'self'
  31. def resolve_relation(scope_model, relation):
  32. """
  33. Transform relation into a model or fully-qualified model string of the form
  34. "app_label.ModelName", relative to scope_model.
  35. The relation argument can be:
  36. * RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case
  37. the model argument will be returned.
  38. * A bare model name without an app_label, in which case scope_model's
  39. app_label will be prepended.
  40. * An "app_label.ModelName" string.
  41. * A model class, which will be returned unchanged.
  42. """
  43. # Check for recursive relations
  44. if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
  45. relation = scope_model
  46. # Look for an "app.Model" relation
  47. if isinstance(relation, str):
  48. if "." not in relation:
  49. relation = "%s.%s" % (scope_model._meta.app_label, relation)
  50. return relation
  51. def lazy_related_operation(function, model, *related_models, **kwargs):
  52. """
  53. Schedule `function` to be called once `model` and all `related_models`
  54. have been imported and registered with the app registry. `function` will
  55. be called with the newly-loaded model classes as its positional arguments,
  56. plus any optional keyword arguments.
  57. The `model` argument must be a model class. Each subsequent positional
  58. argument is another model, or a reference to another model - see
  59. `resolve_relation()` for the various forms these may take. Any relative
  60. references will be resolved relative to `model`.
  61. This is a convenience wrapper for `Apps.lazy_model_operation` - the app
  62. registry model used is the one found in `model._meta.apps`.
  63. """
  64. models = [model] + [resolve_relation(model, rel) for rel in related_models]
  65. model_keys = (make_model_tuple(m) for m in models)
  66. apps = model._meta.apps
  67. return apps.lazy_model_operation(partial(function, **kwargs), *model_keys)
  68. class RelatedField(FieldCacheMixin, Field):
  69. """Base class that all relational fields inherit from."""
  70. # Field flags
  71. one_to_many = False
  72. one_to_one = False
  73. many_to_many = False
  74. many_to_one = False
  75. @cached_property
  76. def related_model(self):
  77. # Can't cache this property until all the models are loaded.
  78. apps.check_models_ready()
  79. return self.remote_field.model
  80. def check(self, **kwargs):
  81. return [
  82. *super().check(**kwargs),
  83. *self._check_related_name_is_valid(),
  84. *self._check_related_query_name_is_valid(),
  85. *self._check_relation_model_exists(),
  86. *self._check_referencing_to_swapped_model(),
  87. *self._check_clashes(),
  88. ]
  89. def _check_related_name_is_valid(self):
  90. import keyword
  91. related_name = self.remote_field.related_name
  92. if related_name is None:
  93. return []
  94. is_valid_id = not keyword.iskeyword(related_name) and related_name.isidentifier()
  95. if not (is_valid_id or related_name.endswith('+')):
  96. return [
  97. checks.Error(
  98. "The name '%s' is invalid related_name for field %s.%s" %
  99. (self.remote_field.related_name, self.model._meta.object_name,
  100. self.name),
  101. hint="Related name must be a valid Python identifier or end with a '+'",
  102. obj=self,
  103. id='fields.E306',
  104. )
  105. ]
  106. return []
  107. def _check_related_query_name_is_valid(self):
  108. if self.remote_field.is_hidden():
  109. return []
  110. rel_query_name = self.related_query_name()
  111. errors = []
  112. if rel_query_name.endswith('_'):
  113. errors.append(
  114. checks.Error(
  115. "Reverse query name '%s' must not end with an underscore."
  116. % (rel_query_name,),
  117. hint=("Add or change a related_name or related_query_name "
  118. "argument for this field."),
  119. obj=self,
  120. id='fields.E308',
  121. )
  122. )
  123. if LOOKUP_SEP in rel_query_name:
  124. errors.append(
  125. checks.Error(
  126. "Reverse query name '%s' must not contain '%s'."
  127. % (rel_query_name, LOOKUP_SEP),
  128. hint=("Add or change a related_name or related_query_name "
  129. "argument for this field."),
  130. obj=self,
  131. id='fields.E309',
  132. )
  133. )
  134. return errors
  135. def _check_relation_model_exists(self):
  136. rel_is_missing = self.remote_field.model not in self.opts.apps.get_models()
  137. rel_is_string = isinstance(self.remote_field.model, str)
  138. model_name = self.remote_field.model if rel_is_string else self.remote_field.model._meta.object_name
  139. if rel_is_missing and (rel_is_string or not self.remote_field.model._meta.swapped):
  140. return [
  141. checks.Error(
  142. "Field defines a relation with model '%s', which is either "
  143. "not installed, or is abstract." % model_name,
  144. obj=self,
  145. id='fields.E300',
  146. )
  147. ]
  148. return []
  149. def _check_referencing_to_swapped_model(self):
  150. if (self.remote_field.model not in self.opts.apps.get_models() and
  151. not isinstance(self.remote_field.model, str) and
  152. self.remote_field.model._meta.swapped):
  153. model = "%s.%s" % (
  154. self.remote_field.model._meta.app_label,
  155. self.remote_field.model._meta.object_name
  156. )
  157. return [
  158. checks.Error(
  159. "Field defines a relation with the model '%s', which has "
  160. "been swapped out." % model,
  161. hint="Update the relation to point at 'settings.%s'." % self.remote_field.model._meta.swappable,
  162. obj=self,
  163. id='fields.E301',
  164. )
  165. ]
  166. return []
  167. def _check_clashes(self):
  168. """Check accessor and reverse query name clashes."""
  169. from django.db.models.base import ModelBase
  170. errors = []
  171. opts = self.model._meta
  172. # `f.remote_field.model` may be a string instead of a model. Skip if model name is
  173. # not resolved.
  174. if not isinstance(self.remote_field.model, ModelBase):
  175. return []
  176. # Consider that we are checking field `Model.foreign` and the models
  177. # are:
  178. #
  179. # class Target(models.Model):
  180. # model = models.IntegerField()
  181. # model_set = models.IntegerField()
  182. #
  183. # class Model(models.Model):
  184. # foreign = models.ForeignKey(Target)
  185. # m2m = models.ManyToManyField(Target)
  186. # rel_opts.object_name == "Target"
  187. rel_opts = self.remote_field.model._meta
  188. # If the field doesn't install a backward relation on the target model
  189. # (so `is_hidden` returns True), then there are no clashes to check
  190. # and we can skip these fields.
  191. rel_is_hidden = self.remote_field.is_hidden()
  192. rel_name = self.remote_field.get_accessor_name() # i. e. "model_set"
  193. rel_query_name = self.related_query_name() # i. e. "model"
  194. field_name = "%s.%s" % (opts.object_name, self.name) # i. e. "Model.field"
  195. # Check clashes between accessor or reverse query name of `field`
  196. # and any other field name -- i.e. accessor for Model.foreign is
  197. # model_set and it clashes with Target.model_set.
  198. potential_clashes = rel_opts.fields + rel_opts.many_to_many
  199. for clash_field in potential_clashes:
  200. clash_name = "%s.%s" % (rel_opts.object_name, clash_field.name) # i.e. "Target.model_set"
  201. if not rel_is_hidden and clash_field.name == rel_name:
  202. errors.append(
  203. checks.Error(
  204. "Reverse accessor for '%s' clashes with field name '%s'." % (field_name, clash_name),
  205. hint=("Rename field '%s', or add/change a related_name "
  206. "argument to the definition for field '%s'.") % (clash_name, field_name),
  207. obj=self,
  208. id='fields.E302',
  209. )
  210. )
  211. if clash_field.name == rel_query_name:
  212. errors.append(
  213. checks.Error(
  214. "Reverse query name for '%s' clashes with field name '%s'." % (field_name, clash_name),
  215. hint=("Rename field '%s', or add/change a related_name "
  216. "argument to the definition for field '%s'.") % (clash_name, field_name),
  217. obj=self,
  218. id='fields.E303',
  219. )
  220. )
  221. # Check clashes between accessors/reverse query names of `field` and
  222. # any other field accessor -- i. e. Model.foreign accessor clashes with
  223. # Model.m2m accessor.
  224. potential_clashes = (r for r in rel_opts.related_objects if r.field is not self)
  225. for clash_field in potential_clashes:
  226. clash_name = "%s.%s" % ( # i. e. "Model.m2m"
  227. clash_field.related_model._meta.object_name,
  228. clash_field.field.name)
  229. if not rel_is_hidden and clash_field.get_accessor_name() == rel_name:
  230. errors.append(
  231. checks.Error(
  232. "Reverse accessor for '%s' clashes with reverse accessor for '%s'." % (field_name, clash_name),
  233. hint=("Add or change a related_name argument "
  234. "to the definition for '%s' or '%s'.") % (field_name, clash_name),
  235. obj=self,
  236. id='fields.E304',
  237. )
  238. )
  239. if clash_field.get_accessor_name() == rel_query_name:
  240. errors.append(
  241. checks.Error(
  242. "Reverse query name for '%s' clashes with reverse query name for '%s'."
  243. % (field_name, clash_name),
  244. hint=("Add or change a related_name argument "
  245. "to the definition for '%s' or '%s'.") % (field_name, clash_name),
  246. obj=self,
  247. id='fields.E305',
  248. )
  249. )
  250. return errors
  251. def db_type(self, connection):
  252. # By default related field will not have a column as it relates to
  253. # columns from another table.
  254. return None
  255. def contribute_to_class(self, cls, name, private_only=False, **kwargs):
  256. super().contribute_to_class(cls, name, private_only=private_only, **kwargs)
  257. self.opts = cls._meta
  258. if not cls._meta.abstract:
  259. if self.remote_field.related_name:
  260. related_name = self.remote_field.related_name
  261. else:
  262. related_name = self.opts.default_related_name
  263. if related_name:
  264. related_name = related_name % {
  265. 'class': cls.__name__.lower(),
  266. 'model_name': cls._meta.model_name.lower(),
  267. 'app_label': cls._meta.app_label.lower()
  268. }
  269. self.remote_field.related_name = related_name
  270. if self.remote_field.related_query_name:
  271. related_query_name = self.remote_field.related_query_name % {
  272. 'class': cls.__name__.lower(),
  273. 'app_label': cls._meta.app_label.lower(),
  274. }
  275. self.remote_field.related_query_name = related_query_name
  276. def resolve_related_class(model, related, field):
  277. field.remote_field.model = related
  278. field.do_related_class(related, model)
  279. lazy_related_operation(resolve_related_class, cls, self.remote_field.model, field=self)
  280. def deconstruct(self):
  281. name, path, args, kwargs = super().deconstruct()
  282. if self.remote_field.limit_choices_to:
  283. kwargs['limit_choices_to'] = self.remote_field.limit_choices_to
  284. if self.remote_field.related_name is not None:
  285. kwargs['related_name'] = self.remote_field.related_name
  286. if self.remote_field.related_query_name is not None:
  287. kwargs['related_query_name'] = self.remote_field.related_query_name
  288. return name, path, args, kwargs
  289. def get_forward_related_filter(self, obj):
  290. """
  291. Return the keyword arguments that when supplied to
  292. self.model.object.filter(), would select all instances related through
  293. this field to the remote obj. This is used to build the querysets
  294. returned by related descriptors. obj is an instance of
  295. self.related_field.model.
  296. """
  297. return {
  298. '%s__%s' % (self.name, rh_field.name): getattr(obj, rh_field.attname)
  299. for _, rh_field in self.related_fields
  300. }
  301. def get_reverse_related_filter(self, obj):
  302. """
  303. Complement to get_forward_related_filter(). Return the keyword
  304. arguments that when passed to self.related_field.model.object.filter()
  305. select all instances of self.related_field.model related through
  306. this field to obj. obj is an instance of self.model.
  307. """
  308. base_filter = {
  309. rh_field.attname: getattr(obj, lh_field.attname)
  310. for lh_field, rh_field in self.related_fields
  311. }
  312. descriptor_filter = self.get_extra_descriptor_filter(obj)
  313. base_q = Q(**base_filter)
  314. if isinstance(descriptor_filter, dict):
  315. return base_q & Q(**descriptor_filter)
  316. elif descriptor_filter:
  317. return base_q & descriptor_filter
  318. return base_q
  319. @property
  320. def swappable_setting(self):
  321. """
  322. Get the setting that this is powered from for swapping, or None
  323. if it's not swapped in / marked with swappable=False.
  324. """
  325. if self.swappable:
  326. # Work out string form of "to"
  327. if isinstance(self.remote_field.model, str):
  328. to_string = self.remote_field.model
  329. else:
  330. to_string = self.remote_field.model._meta.label
  331. return apps.get_swappable_settings_name(to_string)
  332. return None
  333. def set_attributes_from_rel(self):
  334. self.name = (
  335. self.name or
  336. (self.remote_field.model._meta.model_name + '_' + self.remote_field.model._meta.pk.name)
  337. )
  338. if self.verbose_name is None:
  339. self.verbose_name = self.remote_field.model._meta.verbose_name
  340. self.remote_field.set_field_name()
  341. def do_related_class(self, other, cls):
  342. self.set_attributes_from_rel()
  343. self.contribute_to_related_class(other, self.remote_field)
  344. def get_limit_choices_to(self):
  345. """
  346. Return ``limit_choices_to`` for this model field.
  347. If it is a callable, it will be invoked and the result will be
  348. returned.
  349. """
  350. if callable(self.remote_field.limit_choices_to):
  351. return self.remote_field.limit_choices_to()
  352. return self.remote_field.limit_choices_to
  353. def formfield(self, **kwargs):
  354. """
  355. Pass ``limit_choices_to`` to the field being constructed.
  356. Only passes it if there is a type that supports related fields.
  357. This is a similar strategy used to pass the ``queryset`` to the field
  358. being constructed.
  359. """
  360. defaults = {}
  361. if hasattr(self.remote_field, 'get_related_field'):
  362. # If this is a callable, do not invoke it here. Just pass
  363. # it in the defaults for when the form class will later be
  364. # instantiated.
  365. limit_choices_to = self.remote_field.limit_choices_to
  366. defaults.update({
  367. 'limit_choices_to': limit_choices_to,
  368. })
  369. defaults.update(kwargs)
  370. return super().formfield(**defaults)
  371. def related_query_name(self):
  372. """
  373. Define the name that can be used to identify this related object in a
  374. table-spanning query.
  375. """
  376. return self.remote_field.related_query_name or self.remote_field.related_name or self.opts.model_name
  377. @property
  378. def target_field(self):
  379. """
  380. When filtering against this relation, return the field on the remote
  381. model against which the filtering should happen.
  382. """
  383. target_fields = self.get_path_info()[-1].target_fields
  384. if len(target_fields) > 1:
  385. raise exceptions.FieldError(
  386. "The relation has multiple target fields, but only single target field was asked for")
  387. return target_fields[0]
  388. def get_cache_name(self):
  389. return self.name
  390. class ForeignObject(RelatedField):
  391. """
  392. Abstraction of the ForeignKey relation to support multi-column relations.
  393. """
  394. # Field flags
  395. many_to_many = False
  396. many_to_one = True
  397. one_to_many = False
  398. one_to_one = False
  399. requires_unique_target = True
  400. related_accessor_class = ReverseManyToOneDescriptor
  401. forward_related_accessor_class = ForwardManyToOneDescriptor
  402. rel_class = ForeignObjectRel
  403. def __init__(self, to, on_delete, from_fields, to_fields, rel=None, related_name=None,
  404. related_query_name=None, limit_choices_to=None, parent_link=False,
  405. swappable=True, **kwargs):
  406. if rel is None:
  407. rel = self.rel_class(
  408. self, to,
  409. related_name=related_name,
  410. related_query_name=related_query_name,
  411. limit_choices_to=limit_choices_to,
  412. parent_link=parent_link,
  413. on_delete=on_delete,
  414. )
  415. super().__init__(rel=rel, **kwargs)
  416. self.from_fields = from_fields
  417. self.to_fields = to_fields
  418. self.swappable = swappable
  419. def check(self, **kwargs):
  420. return [
  421. *super().check(**kwargs),
  422. *self._check_to_fields_exist(),
  423. *self._check_unique_target(),
  424. ]
  425. def _check_to_fields_exist(self):
  426. # Skip nonexistent models.
  427. if isinstance(self.remote_field.model, str):
  428. return []
  429. errors = []
  430. for to_field in self.to_fields:
  431. if to_field:
  432. try:
  433. self.remote_field.model._meta.get_field(to_field)
  434. except exceptions.FieldDoesNotExist:
  435. errors.append(
  436. checks.Error(
  437. "The to_field '%s' doesn't exist on the related "
  438. "model '%s'."
  439. % (to_field, self.remote_field.model._meta.label),
  440. obj=self,
  441. id='fields.E312',
  442. )
  443. )
  444. return errors
  445. def _check_unique_target(self):
  446. rel_is_string = isinstance(self.remote_field.model, str)
  447. if rel_is_string or not self.requires_unique_target:
  448. return []
  449. try:
  450. self.foreign_related_fields
  451. except exceptions.FieldDoesNotExist:
  452. return []
  453. if not self.foreign_related_fields:
  454. return []
  455. unique_foreign_fields = {
  456. frozenset([f.name])
  457. for f in self.remote_field.model._meta.get_fields()
  458. if getattr(f, 'unique', False)
  459. }
  460. unique_foreign_fields.update({
  461. frozenset(ut)
  462. for ut in self.remote_field.model._meta.unique_together
  463. })
  464. foreign_fields = {f.name for f in self.foreign_related_fields}
  465. has_unique_constraint = any(u <= foreign_fields for u in unique_foreign_fields)
  466. if not has_unique_constraint and len(self.foreign_related_fields) > 1:
  467. field_combination = ', '.join(
  468. "'%s'" % rel_field.name for rel_field in self.foreign_related_fields
  469. )
  470. model_name = self.remote_field.model.__name__
  471. return [
  472. checks.Error(
  473. "No subset of the fields %s on model '%s' is unique."
  474. % (field_combination, model_name),
  475. hint=(
  476. "Add unique=True on any of those fields or add at "
  477. "least a subset of them to a unique_together constraint."
  478. ),
  479. obj=self,
  480. id='fields.E310',
  481. )
  482. ]
  483. elif not has_unique_constraint:
  484. field_name = self.foreign_related_fields[0].name
  485. model_name = self.remote_field.model.__name__
  486. return [
  487. checks.Error(
  488. "'%s.%s' must set unique=True because it is referenced by "
  489. "a foreign key." % (model_name, field_name),
  490. obj=self,
  491. id='fields.E311',
  492. )
  493. ]
  494. else:
  495. return []
  496. def deconstruct(self):
  497. name, path, args, kwargs = super().deconstruct()
  498. kwargs['on_delete'] = self.remote_field.on_delete
  499. kwargs['from_fields'] = self.from_fields
  500. kwargs['to_fields'] = self.to_fields
  501. if self.remote_field.parent_link:
  502. kwargs['parent_link'] = self.remote_field.parent_link
  503. # Work out string form of "to"
  504. if isinstance(self.remote_field.model, str):
  505. kwargs['to'] = self.remote_field.model
  506. else:
  507. kwargs['to'] = "%s.%s" % (
  508. self.remote_field.model._meta.app_label,
  509. self.remote_field.model._meta.object_name,
  510. )
  511. # If swappable is True, then see if we're actually pointing to the target
  512. # of a swap.
  513. swappable_setting = self.swappable_setting
  514. if swappable_setting is not None:
  515. # If it's already a settings reference, error
  516. if hasattr(kwargs['to'], "setting_name"):
  517. if kwargs['to'].setting_name != swappable_setting:
  518. raise ValueError(
  519. "Cannot deconstruct a ForeignKey pointing to a model "
  520. "that is swapped in place of more than one model (%s and %s)"
  521. % (kwargs['to'].setting_name, swappable_setting)
  522. )
  523. # Set it
  524. from django.db.migrations.writer import SettingsReference
  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. return super().get_col(alias, output_field or self.target_field)
  856. class OneToOneField(ForeignKey):
  857. """
  858. A OneToOneField is essentially the same as a ForeignKey, with the exception
  859. that it always carries a "unique" constraint with it and the reverse
  860. relation always returns the object pointed to (since there will only ever
  861. be one), rather than returning a list.
  862. """
  863. # Field flags
  864. many_to_many = False
  865. many_to_one = False
  866. one_to_many = False
  867. one_to_one = True
  868. related_accessor_class = ReverseOneToOneDescriptor
  869. forward_related_accessor_class = ForwardOneToOneDescriptor
  870. rel_class = OneToOneRel
  871. description = _("One-to-one relationship")
  872. def __init__(self, to, on_delete, to_field=None, **kwargs):
  873. kwargs['unique'] = True
  874. super().__init__(to, on_delete, to_field=to_field, **kwargs)
  875. def deconstruct(self):
  876. name, path, args, kwargs = super().deconstruct()
  877. if "unique" in kwargs:
  878. del kwargs['unique']
  879. return name, path, args, kwargs
  880. def formfield(self, **kwargs):
  881. if self.remote_field.parent_link:
  882. return None
  883. return super().formfield(**kwargs)
  884. def save_form_data(self, instance, data):
  885. if isinstance(data, self.remote_field.model):
  886. setattr(instance, self.name, data)
  887. else:
  888. setattr(instance, self.attname, data)
  889. def _check_unique(self, **kwargs):
  890. # Override ForeignKey since check isn't applicable here.
  891. return []
  892. def create_many_to_many_intermediary_model(field, klass):
  893. from django.db import models
  894. def set_managed(model, related, through):
  895. through._meta.managed = model._meta.managed or related._meta.managed
  896. to_model = resolve_relation(klass, field.remote_field.model)
  897. name = '%s_%s' % (klass._meta.object_name, field.name)
  898. lazy_related_operation(set_managed, klass, to_model, name)
  899. to = make_model_tuple(to_model)[1]
  900. from_ = klass._meta.model_name
  901. if to == from_:
  902. to = 'to_%s' % to
  903. from_ = 'from_%s' % from_
  904. meta = type('Meta', (), {
  905. 'db_table': field._get_m2m_db_table(klass._meta),
  906. 'auto_created': klass,
  907. 'app_label': klass._meta.app_label,
  908. 'db_tablespace': klass._meta.db_tablespace,
  909. 'unique_together': (from_, to),
  910. 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to},
  911. 'verbose_name_plural': _('%(from)s-%(to)s relationships') % {'from': from_, 'to': to},
  912. 'apps': field.model._meta.apps,
  913. })
  914. # Construct and return the new class.
  915. return type(name, (models.Model,), {
  916. 'Meta': meta,
  917. '__module__': klass.__module__,
  918. from_: models.ForeignKey(
  919. klass,
  920. related_name='%s+' % name,
  921. db_tablespace=field.db_tablespace,
  922. db_constraint=field.remote_field.db_constraint,
  923. on_delete=CASCADE,
  924. ),
  925. to: models.ForeignKey(
  926. to_model,
  927. related_name='%s+' % name,
  928. db_tablespace=field.db_tablespace,
  929. db_constraint=field.remote_field.db_constraint,
  930. on_delete=CASCADE,
  931. )
  932. })
  933. class ManyToManyField(RelatedField):
  934. """
  935. Provide a many-to-many relation by using an intermediary model that
  936. holds two ForeignKey fields pointed at the two sides of the relation.
  937. Unless a ``through`` model was provided, ManyToManyField will use the
  938. create_many_to_many_intermediary_model factory to automatically generate
  939. the intermediary model.
  940. """
  941. # Field flags
  942. many_to_many = True
  943. many_to_one = False
  944. one_to_many = False
  945. one_to_one = False
  946. rel_class = ManyToManyRel
  947. description = _("Many-to-many relationship")
  948. def __init__(self, to, related_name=None, related_query_name=None,
  949. limit_choices_to=None, symmetrical=None, through=None,
  950. through_fields=None, db_constraint=True, db_table=None,
  951. swappable=True, **kwargs):
  952. try:
  953. to._meta
  954. except AttributeError:
  955. assert isinstance(to, str), (
  956. "%s(%r) is invalid. First parameter to ManyToManyField must be "
  957. "either a model, a model name, or the string %r" %
  958. (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
  959. )
  960. if symmetrical is None:
  961. symmetrical = (to == RECURSIVE_RELATIONSHIP_CONSTANT)
  962. if through is not None:
  963. assert db_table is None, (
  964. "Cannot specify a db_table if an intermediary model is used."
  965. )
  966. kwargs['rel'] = self.rel_class(
  967. self, to,
  968. related_name=related_name,
  969. related_query_name=related_query_name,
  970. limit_choices_to=limit_choices_to,
  971. symmetrical=symmetrical,
  972. through=through,
  973. through_fields=through_fields,
  974. db_constraint=db_constraint,
  975. )
  976. self.has_null_arg = 'null' in kwargs
  977. super().__init__(**kwargs)
  978. self.db_table = db_table
  979. self.swappable = swappable
  980. def check(self, **kwargs):
  981. return [
  982. *super().check(**kwargs),
  983. *self._check_unique(**kwargs),
  984. *self._check_relationship_model(**kwargs),
  985. *self._check_ignored_options(**kwargs),
  986. *self._check_table_uniqueness(**kwargs),
  987. ]
  988. def _check_unique(self, **kwargs):
  989. if self.unique:
  990. return [
  991. checks.Error(
  992. 'ManyToManyFields cannot be unique.',
  993. obj=self,
  994. id='fields.E330',
  995. )
  996. ]
  997. return []
  998. def _check_ignored_options(self, **kwargs):
  999. warnings = []
  1000. if self.has_null_arg:
  1001. warnings.append(
  1002. checks.Warning(
  1003. 'null has no effect on ManyToManyField.',
  1004. obj=self,
  1005. id='fields.W340',
  1006. )
  1007. )
  1008. if self._validators:
  1009. warnings.append(
  1010. checks.Warning(
  1011. 'ManyToManyField does not support validators.',
  1012. obj=self,
  1013. id='fields.W341',
  1014. )
  1015. )
  1016. if (self.remote_field.limit_choices_to and self.remote_field.through and
  1017. not self.remote_field.through._meta.auto_created):
  1018. warnings.append(
  1019. checks.Warning(
  1020. 'limit_choices_to has no effect on ManyToManyField '
  1021. 'with a through model.',
  1022. obj=self,
  1023. id='fields.W343',
  1024. )
  1025. )
  1026. return warnings
  1027. def _check_relationship_model(self, from_model=None, **kwargs):
  1028. if hasattr(self.remote_field.through, '_meta'):
  1029. qualified_model_name = "%s.%s" % (
  1030. self.remote_field.through._meta.app_label, self.remote_field.through.__name__)
  1031. else:
  1032. qualified_model_name = self.remote_field.through
  1033. errors = []
  1034. if self.remote_field.through not in self.opts.apps.get_models(include_auto_created=True):
  1035. # The relationship model is not installed.
  1036. errors.append(
  1037. checks.Error(
  1038. "Field specifies a many-to-many relation through model "
  1039. "'%s', which has not been installed." % qualified_model_name,
  1040. obj=self,
  1041. id='fields.E331',
  1042. )
  1043. )
  1044. else:
  1045. assert from_model is not None, (
  1046. "ManyToManyField with intermediate "
  1047. "tables cannot be checked if you don't pass the model "
  1048. "where the field is attached to."
  1049. )
  1050. # Set some useful local variables
  1051. to_model = resolve_relation(from_model, self.remote_field.model)
  1052. from_model_name = from_model._meta.object_name
  1053. if isinstance(to_model, str):
  1054. to_model_name = to_model
  1055. else:
  1056. to_model_name = to_model._meta.object_name
  1057. relationship_model_name = self.remote_field.through._meta.object_name
  1058. self_referential = from_model == to_model
  1059. # Check symmetrical attribute.
  1060. if (self_referential and self.remote_field.symmetrical and
  1061. not self.remote_field.through._meta.auto_created):
  1062. errors.append(
  1063. checks.Error(
  1064. 'Many-to-many fields with intermediate tables must not be symmetrical.',
  1065. obj=self,
  1066. id='fields.E332',
  1067. )
  1068. )
  1069. # Count foreign keys in intermediate model
  1070. if self_referential:
  1071. seen_self = sum(
  1072. from_model == getattr(field.remote_field, 'model', None)
  1073. for field in self.remote_field.through._meta.fields
  1074. )
  1075. if seen_self > 2 and not self.remote_field.through_fields:
  1076. errors.append(
  1077. checks.Error(
  1078. "The model is used as an intermediate model by "
  1079. "'%s', but it has more than two foreign keys "
  1080. "to '%s', which is ambiguous. You must specify "
  1081. "which two foreign keys Django should use via the "
  1082. "through_fields keyword argument." % (self, from_model_name),
  1083. hint="Use through_fields to specify which two foreign keys Django should use.",
  1084. obj=self.remote_field.through,
  1085. id='fields.E333',
  1086. )
  1087. )
  1088. else:
  1089. # Count foreign keys in relationship model
  1090. seen_from = sum(
  1091. from_model == getattr(field.remote_field, 'model', None)
  1092. for field in self.remote_field.through._meta.fields
  1093. )
  1094. seen_to = sum(
  1095. to_model == getattr(field.remote_field, 'model', None)
  1096. for field in self.remote_field.through._meta.fields
  1097. )
  1098. if seen_from > 1 and not self.remote_field.through_fields:
  1099. errors.append(
  1100. checks.Error(
  1101. ("The model is used as an intermediate model by "
  1102. "'%s', but it has more than one foreign key "
  1103. "from '%s', which is ambiguous. You must specify "
  1104. "which foreign key Django should use via the "
  1105. "through_fields keyword argument.") % (self, from_model_name),
  1106. hint=(
  1107. 'If you want to create a recursive relationship, '
  1108. 'use ForeignKey("self", symmetrical=False, through="%s").'
  1109. ) % relationship_model_name,
  1110. obj=self,
  1111. id='fields.E334',
  1112. )
  1113. )
  1114. if seen_to > 1 and not self.remote_field.through_fields:
  1115. errors.append(
  1116. checks.Error(
  1117. "The model is used as an intermediate model by "
  1118. "'%s', but it has more than one foreign key "
  1119. "to '%s', which is ambiguous. You must specify "
  1120. "which foreign key Django should use via the "
  1121. "through_fields keyword argument." % (self, to_model_name),
  1122. hint=(
  1123. 'If you want to create a recursive relationship, '
  1124. 'use ForeignKey("self", symmetrical=False, through="%s").'
  1125. ) % relationship_model_name,
  1126. obj=self,
  1127. id='fields.E335',
  1128. )
  1129. )
  1130. if seen_from == 0 or seen_to == 0:
  1131. errors.append(
  1132. checks.Error(
  1133. "The model is used as an intermediate model by "
  1134. "'%s', but it does not have a foreign key to '%s' or '%s'." % (
  1135. self, from_model_name, to_model_name
  1136. ),
  1137. obj=self.remote_field.through,
  1138. id='fields.E336',
  1139. )
  1140. )
  1141. # Validate `through_fields`.
  1142. if self.remote_field.through_fields is not None:
  1143. # Validate that we're given an iterable of at least two items
  1144. # and that none of them is "falsy".
  1145. if not (len(self.remote_field.through_fields) >= 2 and
  1146. self.remote_field.through_fields[0] and self.remote_field.through_fields[1]):
  1147. errors.append(
  1148. checks.Error(
  1149. "Field specifies 'through_fields' but does not provide "
  1150. "the names of the two link fields that should be used "
  1151. "for the relation through model '%s'." % qualified_model_name,
  1152. hint="Make sure you specify 'through_fields' as through_fields=('field1', 'field2')",
  1153. obj=self,
  1154. id='fields.E337',
  1155. )
  1156. )
  1157. # Validate the given through fields -- they should be actual
  1158. # fields on the through model, and also be foreign keys to the
  1159. # expected models.
  1160. else:
  1161. assert from_model is not None, (
  1162. "ManyToManyField with intermediate "
  1163. "tables cannot be checked if you don't pass the model "
  1164. "where the field is attached to."
  1165. )
  1166. source, through, target = from_model, self.remote_field.through, self.remote_field.model
  1167. source_field_name, target_field_name = self.remote_field.through_fields[:2]
  1168. for field_name, related_model in ((source_field_name, source),
  1169. (target_field_name, target)):
  1170. possible_field_names = []
  1171. for f in through._meta.fields:
  1172. if hasattr(f, 'remote_field') and getattr(f.remote_field, 'model', None) == related_model:
  1173. possible_field_names.append(f.name)
  1174. if possible_field_names:
  1175. hint = "Did you mean one of the following foreign keys to '%s': %s?" % (
  1176. related_model._meta.object_name,
  1177. ', '.join(possible_field_names),
  1178. )
  1179. else:
  1180. hint = None
  1181. try:
  1182. field = through._meta.get_field(field_name)
  1183. except exceptions.FieldDoesNotExist:
  1184. errors.append(
  1185. checks.Error(
  1186. "The intermediary model '%s' has no field '%s'."
  1187. % (qualified_model_name, field_name),
  1188. hint=hint,
  1189. obj=self,
  1190. id='fields.E338',
  1191. )
  1192. )
  1193. else:
  1194. if not (hasattr(field, 'remote_field') and
  1195. getattr(field.remote_field, 'model', None) == related_model):
  1196. errors.append(
  1197. checks.Error(
  1198. "'%s.%s' is not a foreign key to '%s'." % (
  1199. through._meta.object_name, field_name,
  1200. related_model._meta.object_name,
  1201. ),
  1202. hint=hint,
  1203. obj=self,
  1204. id='fields.E339',
  1205. )
  1206. )
  1207. return errors
  1208. def _check_table_uniqueness(self, **kwargs):
  1209. if isinstance(self.remote_field.through, str) or not self.remote_field.through._meta.managed:
  1210. return []
  1211. registered_tables = {
  1212. model._meta.db_table: model
  1213. for model in self.opts.apps.get_models(include_auto_created=True)
  1214. if model != self.remote_field.through and model._meta.managed
  1215. }
  1216. m2m_db_table = self.m2m_db_table()
  1217. model = registered_tables.get(m2m_db_table)
  1218. # The second condition allows multiple m2m relations on a model if
  1219. # some point to a through model that proxies another through model.
  1220. if model and model._meta.concrete_model != self.remote_field.through._meta.concrete_model:
  1221. if model._meta.auto_created:
  1222. def _get_field_name(model):
  1223. for field in model._meta.auto_created._meta.many_to_many:
  1224. if field.remote_field.through is model:
  1225. return field.name
  1226. opts = model._meta.auto_created._meta
  1227. clashing_obj = '%s.%s' % (opts.label, _get_field_name(model))
  1228. else:
  1229. clashing_obj = '%s' % model._meta.label
  1230. return [
  1231. checks.Error(
  1232. "The field's intermediary table '%s' clashes with the "
  1233. "table name of '%s'." % (m2m_db_table, clashing_obj),
  1234. obj=self,
  1235. id='fields.E340',
  1236. )
  1237. ]
  1238. return []
  1239. def deconstruct(self):
  1240. name, path, args, kwargs = super().deconstruct()
  1241. # Handle the simpler arguments.
  1242. if self.db_table is not None:
  1243. kwargs['db_table'] = self.db_table
  1244. if self.remote_field.db_constraint is not True:
  1245. kwargs['db_constraint'] = self.remote_field.db_constraint
  1246. # Rel needs more work.
  1247. if isinstance(self.remote_field.model, str):
  1248. kwargs['to'] = self.remote_field.model
  1249. else:
  1250. kwargs['to'] = "%s.%s" % (
  1251. self.remote_field.model._meta.app_label,
  1252. self.remote_field.model._meta.object_name,
  1253. )
  1254. if getattr(self.remote_field, 'through', None) is not None:
  1255. if isinstance(self.remote_field.through, str):
  1256. kwargs['through'] = self.remote_field.through
  1257. elif not self.remote_field.through._meta.auto_created:
  1258. kwargs['through'] = "%s.%s" % (
  1259. self.remote_field.through._meta.app_label,
  1260. self.remote_field.through._meta.object_name,
  1261. )
  1262. # If swappable is True, then see if we're actually pointing to the target
  1263. # of a swap.
  1264. swappable_setting = self.swappable_setting
  1265. if swappable_setting is not None:
  1266. # If it's already a settings reference, error.
  1267. if hasattr(kwargs['to'], "setting_name"):
  1268. if kwargs['to'].setting_name != swappable_setting:
  1269. raise ValueError(
  1270. "Cannot deconstruct a ManyToManyField pointing to a "
  1271. "model that is swapped in place of more than one model "
  1272. "(%s and %s)" % (kwargs['to'].setting_name, swappable_setting)
  1273. )
  1274. from django.db.migrations.writer import SettingsReference
  1275. kwargs['to'] = SettingsReference(
  1276. kwargs['to'],
  1277. swappable_setting,
  1278. )
  1279. return name, path, args, kwargs
  1280. def _get_path_info(self, direct=False, filtered_relation=None):
  1281. """Called by both direct and indirect m2m traversal."""
  1282. int_model = self.remote_field.through
  1283. linkfield1 = int_model._meta.get_field(self.m2m_field_name())
  1284. linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name())
  1285. if direct:
  1286. join1infos = linkfield1.get_reverse_path_info()
  1287. join2infos = linkfield2.get_path_info(filtered_relation)
  1288. else:
  1289. join1infos = linkfield2.get_reverse_path_info()
  1290. join2infos = linkfield1.get_path_info(filtered_relation)
  1291. # Get join infos between the last model of join 1 and the first model
  1292. # of join 2. Assume the only reason these may differ is due to model
  1293. # inheritance.
  1294. join1_final = join1infos[-1].to_opts
  1295. join2_initial = join2infos[0].from_opts
  1296. if join1_final is join2_initial:
  1297. intermediate_infos = []
  1298. elif issubclass(join1_final.model, join2_initial.model):
  1299. intermediate_infos = join1_final.get_path_to_parent(join2_initial.model)
  1300. else:
  1301. intermediate_infos = join2_initial.get_path_from_parent(join1_final.model)
  1302. return [*join1infos, *intermediate_infos, *join2infos]
  1303. def get_path_info(self, filtered_relation=None):
  1304. return self._get_path_info(direct=True, filtered_relation=filtered_relation)
  1305. def get_reverse_path_info(self, filtered_relation=None):
  1306. return self._get_path_info(direct=False, filtered_relation=filtered_relation)
  1307. def _get_m2m_db_table(self, opts):
  1308. """
  1309. Function that can be curried to provide the m2m table name for this
  1310. relation.
  1311. """
  1312. if self.remote_field.through is not None:
  1313. return self.remote_field.through._meta.db_table
  1314. elif self.db_table:
  1315. return self.db_table
  1316. else:
  1317. m2m_table_name = '%s_%s' % (utils.strip_quotes(opts.db_table), self.name)
  1318. return utils.truncate_name(m2m_table_name, connection.ops.max_name_length())
  1319. def _get_m2m_attr(self, related, attr):
  1320. """
  1321. Function that can be curried to provide the source accessor or DB
  1322. column name for the m2m table.
  1323. """
  1324. cache_attr = '_m2m_%s_cache' % attr
  1325. if hasattr(self, cache_attr):
  1326. return getattr(self, cache_attr)
  1327. if self.remote_field.through_fields is not None:
  1328. link_field_name = self.remote_field.through_fields[0]
  1329. else:
  1330. link_field_name = None
  1331. for f in self.remote_field.through._meta.fields:
  1332. if (f.is_relation and f.remote_field.model == related.related_model and
  1333. (link_field_name is None or link_field_name == f.name)):
  1334. setattr(self, cache_attr, getattr(f, attr))
  1335. return getattr(self, cache_attr)
  1336. def _get_m2m_reverse_attr(self, related, attr):
  1337. """
  1338. Function that can be curried to provide the related accessor or DB
  1339. column name for the m2m table.
  1340. """
  1341. cache_attr = '_m2m_reverse_%s_cache' % attr
  1342. if hasattr(self, cache_attr):
  1343. return getattr(self, cache_attr)
  1344. found = False
  1345. if self.remote_field.through_fields is not None:
  1346. link_field_name = self.remote_field.through_fields[1]
  1347. else:
  1348. link_field_name = None
  1349. for f in self.remote_field.through._meta.fields:
  1350. if f.is_relation and f.remote_field.model == related.model:
  1351. if link_field_name is None and related.related_model == related.model:
  1352. # If this is an m2m-intermediate to self,
  1353. # the first foreign key you find will be
  1354. # the source column. Keep searching for
  1355. # the second foreign key.
  1356. if found:
  1357. setattr(self, cache_attr, getattr(f, attr))
  1358. break
  1359. else:
  1360. found = True
  1361. elif link_field_name is None or link_field_name == f.name:
  1362. setattr(self, cache_attr, getattr(f, attr))
  1363. break
  1364. return getattr(self, cache_attr)
  1365. def contribute_to_class(self, cls, name, **kwargs):
  1366. # To support multiple relations to self, it's useful to have a non-None
  1367. # related name on symmetrical relations for internal reasons. The
  1368. # concept doesn't make a lot of sense externally ("you want me to
  1369. # specify *what* on my non-reversible relation?!"), so we set it up
  1370. # automatically. The funky name reduces the chance of an accidental
  1371. # clash.
  1372. if self.remote_field.symmetrical and (
  1373. self.remote_field.model == "self" or self.remote_field.model == cls._meta.object_name):
  1374. self.remote_field.related_name = "%s_rel_+" % name
  1375. elif self.remote_field.is_hidden():
  1376. # If the backwards relation is disabled, replace the original
  1377. # related_name with one generated from the m2m field name. Django
  1378. # still uses backwards relations internally and we need to avoid
  1379. # clashes between multiple m2m fields with related_name == '+'.
  1380. self.remote_field.related_name = "_%s_%s_+" % (cls.__name__.lower(), name)
  1381. super().contribute_to_class(cls, name, **kwargs)
  1382. # The intermediate m2m model is not auto created if:
  1383. # 1) There is a manually specified intermediate, or
  1384. # 2) The class owning the m2m field is abstract.
  1385. # 3) The class owning the m2m field has been swapped out.
  1386. if not cls._meta.abstract:
  1387. if self.remote_field.through:
  1388. def resolve_through_model(_, model, field):
  1389. field.remote_field.through = model
  1390. lazy_related_operation(resolve_through_model, cls, self.remote_field.through, field=self)
  1391. elif not cls._meta.swapped:
  1392. self.remote_field.through = create_many_to_many_intermediary_model(self, cls)
  1393. # Add the descriptor for the m2m relation.
  1394. setattr(cls, self.name, ManyToManyDescriptor(self.remote_field, reverse=False))
  1395. # Set up the accessor for the m2m table name for the relation.
  1396. self.m2m_db_table = partial(self._get_m2m_db_table, cls._meta)
  1397. def contribute_to_related_class(self, cls, related):
  1398. # Internal M2Ms (i.e., those with a related name ending with '+')
  1399. # and swapped models don't get a related descriptor.
  1400. if not self.remote_field.is_hidden() and not related.related_model._meta.swapped:
  1401. setattr(cls, related.get_accessor_name(), ManyToManyDescriptor(self.remote_field, reverse=True))
  1402. # Set up the accessors for the column names on the m2m table.
  1403. self.m2m_column_name = partial(self._get_m2m_attr, related, 'column')
  1404. self.m2m_reverse_name = partial(self._get_m2m_reverse_attr, related, 'column')
  1405. self.m2m_field_name = partial(self._get_m2m_attr, related, 'name')
  1406. self.m2m_reverse_field_name = partial(self._get_m2m_reverse_attr, related, 'name')
  1407. get_m2m_rel = partial(self._get_m2m_attr, related, 'remote_field')
  1408. self.m2m_target_field_name = lambda: get_m2m_rel().field_name
  1409. get_m2m_reverse_rel = partial(self._get_m2m_reverse_attr, related, 'remote_field')
  1410. self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name
  1411. def set_attributes_from_rel(self):
  1412. pass
  1413. def value_from_object(self, obj):
  1414. return [] if obj.pk is None else list(getattr(obj, self.attname).all())
  1415. def save_form_data(self, instance, data):
  1416. getattr(instance, self.attname).set(data)
  1417. def formfield(self, *, using=None, **kwargs):
  1418. defaults = {
  1419. 'form_class': forms.ModelMultipleChoiceField,
  1420. 'queryset': self.remote_field.model._default_manager.using(using),
  1421. **kwargs,
  1422. }
  1423. # If initial is passed in, it's a list of related objects, but the
  1424. # MultipleChoiceField takes a list of IDs.
  1425. if defaults.get('initial') is not None:
  1426. initial = defaults['initial']
  1427. if callable(initial):
  1428. initial = initial()
  1429. defaults['initial'] = [i.pk for i in initial]
  1430. return super().formfield(**defaults)
  1431. def db_check(self, connection):
  1432. return None
  1433. def db_type(self, connection):
  1434. # A ManyToManyField is not represented by a single column,
  1435. # so return None.
  1436. return None
  1437. def db_parameters(self, connection):
  1438. return {"type": None, "check": None}