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 67 KiB

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