related.py 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593
  1. from __future__ import unicode_literals
  2. from operator import attrgetter
  3. import warnings
  4. from django.apps import apps
  5. from django.core import checks
  6. from django.core.exceptions import FieldDoesNotExist
  7. from django.db import connection, connections, router, transaction
  8. from django.db.backends import utils
  9. from django.db.models import signals, Q
  10. from django.db.models.deletion import SET_NULL, SET_DEFAULT, CASCADE
  11. from django.db.models.fields import (AutoField, Field, IntegerField,
  12. PositiveIntegerField, PositiveSmallIntegerField, BLANK_CHOICE_DASH)
  13. from django.db.models.lookups import IsNull
  14. from django.db.models.query import QuerySet
  15. from django.db.models.query_utils import PathInfo
  16. from django.utils.encoding import force_text, smart_text
  17. from django.utils import six
  18. from django.utils.deprecation import RemovedInDjango20Warning
  19. from django.utils.translation import ugettext_lazy as _
  20. from django.utils.functional import curry, cached_property
  21. from django.core import exceptions
  22. from django import forms
  23. RECURSIVE_RELATIONSHIP_CONSTANT = 'self'
  24. def add_lazy_relation(cls, field, relation, operation):
  25. """
  26. Adds a lookup on ``cls`` when a related field is defined using a string,
  27. i.e.::
  28. class MyModel(Model):
  29. fk = ForeignKey("AnotherModel")
  30. This string can be:
  31. * RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate a recursive
  32. relation.
  33. * The name of a model (i.e "AnotherModel") to indicate another model in
  34. the same app.
  35. * An app-label and model name (i.e. "someapp.AnotherModel") to indicate
  36. another model in a different app.
  37. If the other model hasn't yet been loaded -- almost a given if you're using
  38. lazy relationships -- then the relation won't be set up until the
  39. class_prepared signal fires at the end of model initialization.
  40. operation is the work that must be performed once the relation can be resolved.
  41. """
  42. # Check for recursive relations
  43. if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
  44. app_label = cls._meta.app_label
  45. model_name = cls.__name__
  46. else:
  47. # Look for an "app.Model" relation
  48. if isinstance(relation, six.string_types):
  49. try:
  50. app_label, model_name = relation.split(".")
  51. except ValueError:
  52. # If we can't split, assume a model in current app
  53. app_label = cls._meta.app_label
  54. model_name = relation
  55. else:
  56. # it's actually a model class
  57. app_label = relation._meta.app_label
  58. model_name = relation._meta.object_name
  59. # Try to look up the related model, and if it's already loaded resolve the
  60. # string right away. If get_registered_model raises a LookupError, it means
  61. # that the related model isn't loaded yet, so we need to pend the relation
  62. # until the class is prepared.
  63. try:
  64. model = cls._meta.apps.get_registered_model(app_label, model_name)
  65. except LookupError:
  66. key = (app_label, model_name)
  67. value = (cls, field, operation)
  68. cls._meta.apps._pending_lookups.setdefault(key, []).append(value)
  69. else:
  70. operation(field, model, cls)
  71. def do_pending_lookups(sender, **kwargs):
  72. """
  73. Handle any pending relations to the sending model. Sent from class_prepared.
  74. """
  75. key = (sender._meta.app_label, sender.__name__)
  76. for cls, field, operation in sender._meta.apps._pending_lookups.pop(key, []):
  77. operation(field, sender, cls)
  78. signals.class_prepared.connect(do_pending_lookups)
  79. class RelatedField(Field):
  80. # Field flags
  81. one_to_many = False
  82. one_to_one = False
  83. many_to_many = False
  84. many_to_one = False
  85. @cached_property
  86. def related_model(self):
  87. # Can't cache this property until all the models are loaded.
  88. apps.check_models_ready()
  89. return self.rel.to
  90. def check(self, **kwargs):
  91. errors = super(RelatedField, self).check(**kwargs)
  92. errors.extend(self._check_related_name_is_valid())
  93. errors.extend(self._check_relation_model_exists())
  94. errors.extend(self._check_referencing_to_swapped_model())
  95. errors.extend(self._check_clashes())
  96. return errors
  97. def _check_related_name_is_valid(self):
  98. import re
  99. import keyword
  100. related_name = self.rel.related_name
  101. is_valid_id = (related_name and re.match('^[a-zA-Z_][a-zA-Z0-9_]*$', related_name)
  102. and not keyword.iskeyword(related_name))
  103. if related_name and not (is_valid_id or related_name.endswith('+')):
  104. return [
  105. checks.Error(
  106. "The name '%s' is invalid related_name for field %s.%s" %
  107. (self.rel.related_name, self.model._meta.object_name,
  108. self.name),
  109. hint="Related name must be a valid Python identifier or end with a '+'",
  110. obj=self,
  111. id='fields.E306',
  112. )
  113. ]
  114. return []
  115. def _check_relation_model_exists(self):
  116. rel_is_missing = self.rel.to not in apps.get_models()
  117. rel_is_string = isinstance(self.rel.to, six.string_types)
  118. model_name = self.rel.to if rel_is_string else self.rel.to._meta.object_name
  119. if rel_is_missing and (rel_is_string or not self.rel.to._meta.swapped):
  120. return [
  121. checks.Error(
  122. ("Field defines a relation with model '%s', which "
  123. "is either not installed, or is abstract.") % model_name,
  124. hint=None,
  125. obj=self,
  126. id='fields.E300',
  127. )
  128. ]
  129. return []
  130. def _check_referencing_to_swapped_model(self):
  131. if (self.rel.to not in apps.get_models() and
  132. not isinstance(self.rel.to, six.string_types) and
  133. self.rel.to._meta.swapped):
  134. model = "%s.%s" % (
  135. self.rel.to._meta.app_label,
  136. self.rel.to._meta.object_name
  137. )
  138. return [
  139. checks.Error(
  140. ("Field defines a relation with the model '%s', "
  141. "which has been swapped out.") % model,
  142. hint="Update the relation to point at 'settings.%s'." % self.rel.to._meta.swappable,
  143. obj=self,
  144. id='fields.E301',
  145. )
  146. ]
  147. return []
  148. def _check_clashes(self):
  149. """ Check accessor and reverse query name clashes. """
  150. from django.db.models.base import ModelBase
  151. errors = []
  152. opts = self.model._meta
  153. # `f.rel.to` may be a string instead of a model. Skip if model name is
  154. # not resolved.
  155. if not isinstance(self.rel.to, ModelBase):
  156. return []
  157. # If the field doesn't install backward relation on the target model (so
  158. # `is_hidden` returns True), then there are no clashes to check and we
  159. # can skip these fields.
  160. if self.rel.is_hidden():
  161. return []
  162. try:
  163. self.rel
  164. except AttributeError:
  165. return []
  166. # Consider that we are checking field `Model.foreign` and the models
  167. # are:
  168. #
  169. # class Target(models.Model):
  170. # model = models.IntegerField()
  171. # model_set = models.IntegerField()
  172. #
  173. # class Model(models.Model):
  174. # foreign = models.ForeignKey(Target)
  175. # m2m = models.ManyToManyField(Target)
  176. rel_opts = self.rel.to._meta
  177. # rel_opts.object_name == "Target"
  178. rel_name = self.rel.get_accessor_name() # i. e. "model_set"
  179. rel_query_name = self.related_query_name() # i. e. "model"
  180. field_name = "%s.%s" % (opts.object_name,
  181. self.name) # i. e. "Model.field"
  182. # Check clashes between accessor or reverse query name of `field`
  183. # and any other field name -- i.e. accessor for Model.foreign is
  184. # model_set and it clashes with Target.model_set.
  185. potential_clashes = rel_opts.fields + rel_opts.many_to_many
  186. for clash_field in potential_clashes:
  187. clash_name = "%s.%s" % (rel_opts.object_name,
  188. clash_field.name) # i. e. "Target.model_set"
  189. if clash_field.name == rel_name:
  190. errors.append(
  191. checks.Error(
  192. "Reverse accessor for '%s' clashes with field name '%s'." % (field_name, clash_name),
  193. hint=("Rename field '%s', or add/change a related_name "
  194. "argument to the definition for field '%s'.") % (clash_name, field_name),
  195. obj=self,
  196. id='fields.E302',
  197. )
  198. )
  199. if clash_field.name == rel_query_name:
  200. errors.append(
  201. checks.Error(
  202. "Reverse query name for '%s' clashes with field name '%s'." % (field_name, clash_name),
  203. hint=("Rename field '%s', or add/change a related_name "
  204. "argument to the definition for field '%s'.") % (clash_name, field_name),
  205. obj=self,
  206. id='fields.E303',
  207. )
  208. )
  209. # Check clashes between accessors/reverse query names of `field` and
  210. # any other field accessor -- i. e. Model.foreign accessor clashes with
  211. # Model.m2m accessor.
  212. potential_clashes = (r for r in rel_opts.related_objects if r.field is not self)
  213. for clash_field in potential_clashes:
  214. clash_name = "%s.%s" % ( # i. e. "Model.m2m"
  215. clash_field.related_model._meta.object_name,
  216. clash_field.field.name)
  217. if clash_field.get_accessor_name() == rel_name:
  218. errors.append(
  219. checks.Error(
  220. "Reverse accessor for '%s' clashes with reverse accessor for '%s'." % (field_name, clash_name),
  221. hint=("Add or change a related_name argument "
  222. "to the definition for '%s' or '%s'.") % (field_name, clash_name),
  223. obj=self,
  224. id='fields.E304',
  225. )
  226. )
  227. if clash_field.get_accessor_name() == rel_query_name:
  228. errors.append(
  229. checks.Error(
  230. "Reverse query name for '%s' clashes with reverse query name for '%s'."
  231. % (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.E305',
  236. )
  237. )
  238. return errors
  239. def db_type(self, connection):
  240. '''By default related field will not have a column
  241. as it relates columns to another table'''
  242. return None
  243. def contribute_to_class(self, cls, name, virtual_only=False):
  244. sup = super(RelatedField, self)
  245. # Store the opts for related_query_name()
  246. self.opts = cls._meta
  247. if hasattr(sup, 'contribute_to_class'):
  248. sup.contribute_to_class(cls, name, virtual_only=virtual_only)
  249. if not cls._meta.abstract and self.rel.related_name:
  250. related_name = force_text(self.rel.related_name) % {
  251. 'class': cls.__name__.lower(),
  252. 'app_label': cls._meta.app_label.lower()
  253. }
  254. self.rel.related_name = related_name
  255. other = self.rel.to
  256. if isinstance(other, six.string_types) or other._meta.pk is None:
  257. def resolve_related_class(field, model, cls):
  258. field.rel.to = model
  259. field.do_related_class(model, cls)
  260. add_lazy_relation(cls, self, other, resolve_related_class)
  261. else:
  262. self.do_related_class(other, cls)
  263. @property
  264. def swappable_setting(self):
  265. """
  266. Gets the setting that this is powered from for swapping, or None
  267. if it's not swapped in / marked with swappable=False.
  268. """
  269. if self.swappable:
  270. # Work out string form of "to"
  271. if isinstance(self.rel.to, six.string_types):
  272. to_string = self.rel.to
  273. else:
  274. to_string = "%s.%s" % (
  275. self.rel.to._meta.app_label,
  276. self.rel.to._meta.object_name,
  277. )
  278. # See if anything swapped/swappable matches
  279. for model in apps.get_models(include_swapped=True):
  280. if model._meta.swapped:
  281. if model._meta.swapped == to_string:
  282. return model._meta.swappable
  283. if ("%s.%s" % (model._meta.app_label, model._meta.object_name)) == to_string and model._meta.swappable:
  284. return model._meta.swappable
  285. return None
  286. def set_attributes_from_rel(self):
  287. self.name = self.name or (self.rel.to._meta.model_name + '_' + self.rel.to._meta.pk.name)
  288. if self.verbose_name is None:
  289. self.verbose_name = self.rel.to._meta.verbose_name
  290. self.rel.set_field_name()
  291. @property
  292. def related(self):
  293. warnings.warn(
  294. "Usage of field.related has been deprecated. Use field.rel instead.",
  295. RemovedInDjango20Warning, 2)
  296. return self.rel
  297. def do_related_class(self, other, cls):
  298. self.set_attributes_from_rel()
  299. if not cls._meta.abstract:
  300. self.contribute_to_related_class(other, self.rel)
  301. def get_limit_choices_to(self):
  302. """Returns 'limit_choices_to' for this model field.
  303. If it is a callable, it will be invoked and the result will be
  304. returned.
  305. """
  306. if callable(self.rel.limit_choices_to):
  307. return self.rel.limit_choices_to()
  308. return self.rel.limit_choices_to
  309. def formfield(self, **kwargs):
  310. """Passes ``limit_choices_to`` to field being constructed.
  311. Only passes it if there is a type that supports related fields.
  312. This is a similar strategy used to pass the ``queryset`` to the field
  313. being constructed.
  314. """
  315. defaults = {}
  316. if hasattr(self.rel, 'get_related_field'):
  317. # If this is a callable, do not invoke it here. Just pass
  318. # it in the defaults for when the form class will later be
  319. # instantiated.
  320. limit_choices_to = self.rel.limit_choices_to
  321. defaults.update({
  322. 'limit_choices_to': limit_choices_to,
  323. })
  324. defaults.update(kwargs)
  325. return super(RelatedField, self).formfield(**defaults)
  326. def related_query_name(self):
  327. # This method defines the name that can be used to identify this
  328. # related object in a table-spanning query. It uses the lower-cased
  329. # object_name by default, but this can be overridden with the
  330. # "related_name" option.
  331. return self.rel.related_query_name or self.rel.related_name or self.opts.model_name
  332. class SingleRelatedObjectDescriptor(object):
  333. # This class provides the functionality that makes the related-object
  334. # managers available as attributes on a model class, for fields that have
  335. # a single "remote" value, on the class pointed to by a related field.
  336. # In the example "place.restaurant", the restaurant attribute is a
  337. # SingleRelatedObjectDescriptor instance.
  338. def __init__(self, related):
  339. self.related = related
  340. self.cache_name = related.get_cache_name()
  341. @cached_property
  342. def RelatedObjectDoesNotExist(self):
  343. # The exception isn't created at initialization time for the sake of
  344. # consistency with `ReverseSingleRelatedObjectDescriptor`.
  345. return type(
  346. str('RelatedObjectDoesNotExist'),
  347. (self.related.related_model.DoesNotExist, AttributeError),
  348. {}
  349. )
  350. def is_cached(self, instance):
  351. return hasattr(instance, self.cache_name)
  352. def get_queryset(self, **hints):
  353. manager = self.related.related_model._default_manager
  354. # If the related manager indicates that it should be used for
  355. # related fields, respect that.
  356. if not getattr(manager, 'use_for_related_fields', False):
  357. manager = self.related.related_model._base_manager
  358. return manager.db_manager(hints=hints).all()
  359. def get_prefetch_queryset(self, instances, queryset=None):
  360. if queryset is None:
  361. queryset = self.get_queryset()
  362. queryset._add_hints(instance=instances[0])
  363. rel_obj_attr = attrgetter(self.related.field.attname)
  364. instance_attr = lambda obj: obj._get_pk_val()
  365. instances_dict = {instance_attr(inst): inst for inst in instances}
  366. query = {'%s__in' % self.related.field.name: instances}
  367. queryset = queryset.filter(**query)
  368. # Since we're going to assign directly in the cache,
  369. # we must manage the reverse relation cache manually.
  370. rel_obj_cache_name = self.related.field.get_cache_name()
  371. for rel_obj in queryset:
  372. instance = instances_dict[rel_obj_attr(rel_obj)]
  373. setattr(rel_obj, rel_obj_cache_name, instance)
  374. return queryset, rel_obj_attr, instance_attr, True, self.cache_name
  375. def __get__(self, instance, instance_type=None):
  376. if instance is None:
  377. return self
  378. try:
  379. rel_obj = getattr(instance, self.cache_name)
  380. except AttributeError:
  381. related_pk = instance._get_pk_val()
  382. if related_pk is None:
  383. rel_obj = None
  384. else:
  385. params = {}
  386. for lh_field, rh_field in self.related.field.related_fields:
  387. params['%s__%s' % (self.related.field.name, rh_field.name)] = getattr(instance, rh_field.attname)
  388. try:
  389. rel_obj = self.get_queryset(instance=instance).get(**params)
  390. except self.related.related_model.DoesNotExist:
  391. rel_obj = None
  392. else:
  393. setattr(rel_obj, self.related.field.get_cache_name(), instance)
  394. setattr(instance, self.cache_name, rel_obj)
  395. if rel_obj is None:
  396. raise self.RelatedObjectDoesNotExist(
  397. "%s has no %s." % (
  398. instance.__class__.__name__,
  399. self.related.get_accessor_name()
  400. )
  401. )
  402. else:
  403. return rel_obj
  404. def __set__(self, instance, value):
  405. # The similarity of the code below to the code in
  406. # ReverseSingleRelatedObjectDescriptor is annoying, but there's a bunch
  407. # of small differences that would make a common base class convoluted.
  408. # If null=True, we can assign null here, but otherwise the value needs
  409. # to be an instance of the related class.
  410. if value is None and self.related.field.null is False:
  411. raise ValueError(
  412. 'Cannot assign None: "%s.%s" does not allow null values.' % (
  413. instance._meta.object_name,
  414. self.related.get_accessor_name(),
  415. )
  416. )
  417. elif value is not None and not isinstance(value, self.related.related_model):
  418. raise ValueError(
  419. 'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
  420. value,
  421. instance._meta.object_name,
  422. self.related.get_accessor_name(),
  423. self.related.opts.object_name,
  424. )
  425. )
  426. elif value is not None:
  427. if instance._state.db is None:
  428. instance._state.db = router.db_for_write(instance.__class__, instance=value)
  429. elif value._state.db is None:
  430. value._state.db = router.db_for_write(value.__class__, instance=instance)
  431. elif value._state.db is not None and instance._state.db is not None:
  432. if not router.allow_relation(value, instance):
  433. raise ValueError('Cannot assign "%r": the current database router prevents this relation.' % value)
  434. related_pk = tuple(getattr(instance, field.attname) for field in self.related.field.foreign_related_fields)
  435. if None in related_pk:
  436. raise ValueError(
  437. 'Cannot assign "%r": "%s" instance isn\'t saved in the database.' %
  438. (value, instance._meta.object_name)
  439. )
  440. # Set the value of the related field to the value of the related object's related field
  441. for index, field in enumerate(self.related.field.local_related_fields):
  442. setattr(value, field.attname, related_pk[index])
  443. # Since we already know what the related object is, seed the related
  444. # object caches now, too. This avoids another db hit if you get the
  445. # object you just set.
  446. setattr(instance, self.cache_name, value)
  447. setattr(value, self.related.field.get_cache_name(), instance)
  448. class ReverseSingleRelatedObjectDescriptor(object):
  449. # This class provides the functionality that makes the related-object
  450. # managers available as attributes on a model class, for fields that have
  451. # a single "remote" value, on the class that defines the related field.
  452. # In the example "choice.poll", the poll attribute is a
  453. # ReverseSingleRelatedObjectDescriptor instance.
  454. def __init__(self, field_with_rel):
  455. self.field = field_with_rel
  456. self.cache_name = self.field.get_cache_name()
  457. @cached_property
  458. def RelatedObjectDoesNotExist(self):
  459. # The exception can't be created at initialization time since the
  460. # related model might not be resolved yet; `rel.to` might still be
  461. # a string model reference.
  462. return type(
  463. str('RelatedObjectDoesNotExist'),
  464. (self.field.rel.to.DoesNotExist, AttributeError),
  465. {}
  466. )
  467. def is_cached(self, instance):
  468. return hasattr(instance, self.cache_name)
  469. def get_queryset(self, **hints):
  470. manager = self.field.rel.to._default_manager
  471. # If the related manager indicates that it should be used for
  472. # related fields, respect that.
  473. if not getattr(manager, 'use_for_related_fields', False):
  474. manager = self.field.rel.to._base_manager
  475. return manager.db_manager(hints=hints).all()
  476. def get_prefetch_queryset(self, instances, queryset=None):
  477. if queryset is None:
  478. queryset = self.get_queryset()
  479. queryset._add_hints(instance=instances[0])
  480. rel_obj_attr = self.field.get_foreign_related_value
  481. instance_attr = self.field.get_local_related_value
  482. instances_dict = {instance_attr(inst): inst for inst in instances}
  483. related_field = self.field.foreign_related_fields[0]
  484. # FIXME: This will need to be revisited when we introduce support for
  485. # composite fields. In the meantime we take this practical approach to
  486. # solve a regression on 1.6 when the reverse manager in hidden
  487. # (related_name ends with a '+'). Refs #21410.
  488. # The check for len(...) == 1 is a special case that allows the query
  489. # to be join-less and smaller. Refs #21760.
  490. if self.field.rel.is_hidden() or len(self.field.foreign_related_fields) == 1:
  491. query = {'%s__in' % related_field.name: set(instance_attr(inst)[0] for inst in instances)}
  492. else:
  493. query = {'%s__in' % self.field.related_query_name(): instances}
  494. queryset = queryset.filter(**query)
  495. # Since we're going to assign directly in the cache,
  496. # we must manage the reverse relation cache manually.
  497. if not self.field.rel.multiple:
  498. rel_obj_cache_name = self.field.rel.get_cache_name()
  499. for rel_obj in queryset:
  500. instance = instances_dict[rel_obj_attr(rel_obj)]
  501. setattr(rel_obj, rel_obj_cache_name, instance)
  502. return queryset, rel_obj_attr, instance_attr, True, self.cache_name
  503. def __get__(self, instance, instance_type=None):
  504. if instance is None:
  505. return self
  506. try:
  507. rel_obj = getattr(instance, self.cache_name)
  508. except AttributeError:
  509. val = self.field.get_local_related_value(instance)
  510. if None in val:
  511. rel_obj = None
  512. else:
  513. params = {
  514. rh_field.attname: getattr(instance, lh_field.attname)
  515. for lh_field, rh_field in self.field.related_fields}
  516. qs = self.get_queryset(instance=instance)
  517. extra_filter = self.field.get_extra_descriptor_filter(instance)
  518. if isinstance(extra_filter, dict):
  519. params.update(extra_filter)
  520. qs = qs.filter(**params)
  521. else:
  522. qs = qs.filter(extra_filter, **params)
  523. # Assuming the database enforces foreign keys, this won't fail.
  524. rel_obj = qs.get()
  525. if not self.field.rel.multiple:
  526. setattr(rel_obj, self.field.rel.get_cache_name(), instance)
  527. setattr(instance, self.cache_name, rel_obj)
  528. if rel_obj is None and not self.field.null:
  529. raise self.RelatedObjectDoesNotExist(
  530. "%s has no %s." % (self.field.model.__name__, self.field.name)
  531. )
  532. else:
  533. return rel_obj
  534. def __set__(self, instance, value):
  535. # If null=True, we can assign null here, but otherwise the value needs
  536. # to be an instance of the related class.
  537. if value is None and self.field.null is False:
  538. raise ValueError(
  539. 'Cannot assign None: "%s.%s" does not allow null values.' %
  540. (instance._meta.object_name, self.field.name)
  541. )
  542. elif value is not None and not isinstance(value, self.field.rel.to):
  543. raise ValueError(
  544. 'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
  545. value,
  546. instance._meta.object_name,
  547. self.field.name,
  548. self.field.rel.to._meta.object_name,
  549. )
  550. )
  551. elif value is not None:
  552. if instance._state.db is None:
  553. instance._state.db = router.db_for_write(instance.__class__, instance=value)
  554. elif value._state.db is None:
  555. value._state.db = router.db_for_write(value.__class__, instance=instance)
  556. elif value._state.db is not None and instance._state.db is not None:
  557. if not router.allow_relation(value, instance):
  558. raise ValueError('Cannot assign "%r": the current database router prevents this relation.' % value)
  559. # If we're setting the value of a OneToOneField to None, we need to clear
  560. # out the cache on any old related object. Otherwise, deleting the
  561. # previously-related object will also cause this object to be deleted,
  562. # which is wrong.
  563. if value is None:
  564. # Look up the previously-related object, which may still be available
  565. # since we've not yet cleared out the related field.
  566. # Use the cache directly, instead of the accessor; if we haven't
  567. # populated the cache, then we don't care - we're only accessing
  568. # the object to invalidate the accessor cache, so there's no
  569. # need to populate the cache just to expire it again.
  570. related = getattr(instance, self.cache_name, None)
  571. # If we've got an old related object, we need to clear out its
  572. # cache. This cache also might not exist if the related object
  573. # hasn't been accessed yet.
  574. if related is not None:
  575. setattr(related, self.field.rel.get_cache_name(), None)
  576. for lh_field, rh_field in self.field.related_fields:
  577. setattr(instance, lh_field.attname, None)
  578. # Set the values of the related field.
  579. else:
  580. for lh_field, rh_field in self.field.related_fields:
  581. pk = value._get_pk_val()
  582. if pk is None:
  583. raise ValueError(
  584. 'Cannot assign "%r": "%s" instance isn\'t saved in the database.' %
  585. (value, self.field.rel.to._meta.object_name)
  586. )
  587. setattr(instance, lh_field.attname, getattr(value, rh_field.attname))
  588. # Since we already know what the related object is, seed the related
  589. # object caches now, too. This avoids another db hit if you get the
  590. # object you just set.
  591. setattr(instance, self.cache_name, value)
  592. if value is not None and not self.field.rel.multiple:
  593. setattr(value, self.field.rel.get_cache_name(), instance)
  594. def create_foreign_related_manager(superclass, rel_field, rel_model):
  595. class RelatedManager(superclass):
  596. def __init__(self, instance):
  597. super(RelatedManager, self).__init__()
  598. self.instance = instance
  599. self.core_filters = {'%s__exact' % rel_field.name: instance}
  600. self.model = rel_model
  601. def __call__(self, **kwargs):
  602. # We use **kwargs rather than a kwarg argument to enforce the
  603. # `manager='manager_name'` syntax.
  604. manager = getattr(self.model, kwargs.pop('manager'))
  605. manager_class = create_foreign_related_manager(manager.__class__, rel_field, rel_model)
  606. return manager_class(self.instance)
  607. do_not_call_in_templates = True
  608. def get_queryset(self):
  609. try:
  610. return self.instance._prefetched_objects_cache[rel_field.related_query_name()]
  611. except (AttributeError, KeyError):
  612. db = self._db or router.db_for_read(self.model, instance=self.instance)
  613. empty_strings_as_null = connections[db].features.interprets_empty_strings_as_nulls
  614. qs = super(RelatedManager, self).get_queryset()
  615. qs._add_hints(instance=self.instance)
  616. if self._db:
  617. qs = qs.using(self._db)
  618. qs = qs.filter(**self.core_filters)
  619. for field in rel_field.foreign_related_fields:
  620. val = getattr(self.instance, field.attname)
  621. if val is None or (val == '' and empty_strings_as_null):
  622. return qs.none()
  623. qs._known_related_objects = {rel_field: {self.instance.pk: self.instance}}
  624. return qs
  625. def get_prefetch_queryset(self, instances, queryset=None):
  626. if queryset is None:
  627. queryset = super(RelatedManager, self).get_queryset()
  628. queryset._add_hints(instance=instances[0])
  629. queryset = queryset.using(queryset._db or self._db)
  630. rel_obj_attr = rel_field.get_local_related_value
  631. instance_attr = rel_field.get_foreign_related_value
  632. instances_dict = {instance_attr(inst): inst for inst in instances}
  633. query = {'%s__in' % rel_field.name: instances}
  634. queryset = queryset.filter(**query)
  635. # Since we just bypassed this class' get_queryset(), we must manage
  636. # the reverse relation manually.
  637. for rel_obj in queryset:
  638. instance = instances_dict[rel_obj_attr(rel_obj)]
  639. setattr(rel_obj, rel_field.name, instance)
  640. cache_name = rel_field.related_query_name()
  641. return queryset, rel_obj_attr, instance_attr, False, cache_name
  642. def add(self, *objs):
  643. objs = list(objs)
  644. db = router.db_for_write(self.model, instance=self.instance)
  645. with transaction.atomic(using=db, savepoint=False):
  646. for obj in objs:
  647. if not isinstance(obj, self.model):
  648. raise TypeError("'%s' instance expected, got %r" %
  649. (self.model._meta.object_name, obj))
  650. setattr(obj, rel_field.name, self.instance)
  651. obj.save()
  652. add.alters_data = True
  653. def create(self, **kwargs):
  654. kwargs[rel_field.name] = self.instance
  655. db = router.db_for_write(self.model, instance=self.instance)
  656. return super(RelatedManager, self.db_manager(db)).create(**kwargs)
  657. create.alters_data = True
  658. def get_or_create(self, **kwargs):
  659. kwargs[rel_field.name] = self.instance
  660. db = router.db_for_write(self.model, instance=self.instance)
  661. return super(RelatedManager, self.db_manager(db)).get_or_create(**kwargs)
  662. get_or_create.alters_data = True
  663. def update_or_create(self, **kwargs):
  664. kwargs[rel_field.name] = self.instance
  665. db = router.db_for_write(self.model, instance=self.instance)
  666. return super(RelatedManager, self.db_manager(db)).update_or_create(**kwargs)
  667. update_or_create.alters_data = True
  668. # remove() and clear() are only provided if the ForeignKey can have a value of null.
  669. if rel_field.null:
  670. def remove(self, *objs, **kwargs):
  671. if not objs:
  672. return
  673. bulk = kwargs.pop('bulk', True)
  674. val = rel_field.get_foreign_related_value(self.instance)
  675. old_ids = set()
  676. for obj in objs:
  677. # Is obj actually part of this descriptor set?
  678. if rel_field.get_local_related_value(obj) == val:
  679. old_ids.add(obj.pk)
  680. else:
  681. raise rel_field.rel.to.DoesNotExist("%r is not related to %r." % (obj, self.instance))
  682. self._clear(self.filter(pk__in=old_ids), bulk)
  683. remove.alters_data = True
  684. def clear(self, **kwargs):
  685. bulk = kwargs.pop('bulk', True)
  686. self._clear(self, bulk)
  687. clear.alters_data = True
  688. def _clear(self, queryset, bulk):
  689. db = router.db_for_write(self.model, instance=self.instance)
  690. queryset = queryset.using(db)
  691. if bulk:
  692. # `QuerySet.update()` is intrinsically atomic.
  693. queryset.update(**{rel_field.name: None})
  694. else:
  695. with transaction.atomic(using=db, savepoint=False):
  696. for obj in queryset:
  697. setattr(obj, rel_field.name, None)
  698. obj.save(update_fields=[rel_field.name])
  699. _clear.alters_data = True
  700. return RelatedManager
  701. class ForeignRelatedObjectsDescriptor(object):
  702. # This class provides the functionality that makes the related-object
  703. # managers available as attributes on a model class, for fields that have
  704. # multiple "remote" values and have a ForeignKey pointed at them by
  705. # some other model. In the example "poll.choice_set", the choice_set
  706. # attribute is a ForeignRelatedObjectsDescriptor instance.
  707. def __init__(self, related):
  708. self.related = related # RelatedObject instance
  709. def __get__(self, instance, instance_type=None):
  710. if instance is None:
  711. return self
  712. return self.related_manager_cls(instance)
  713. def __set__(self, instance, value):
  714. # Force evaluation of `value` in case it's a queryset whose
  715. # value could be affected by `manager.clear()`. Refs #19816.
  716. value = tuple(value)
  717. manager = self.__get__(instance)
  718. db = router.db_for_write(manager.model, instance=manager.instance)
  719. with transaction.atomic(using=db, savepoint=False):
  720. # If the foreign key can support nulls, then completely clear the related set.
  721. # Otherwise, just move the named objects into the set.
  722. if self.related.field.null:
  723. manager.clear()
  724. manager.add(*value)
  725. @cached_property
  726. def related_manager_cls(self):
  727. # Dynamically create a class that subclasses the related model's default
  728. # manager.
  729. return create_foreign_related_manager(
  730. self.related.related_model._default_manager.__class__,
  731. self.related.field,
  732. self.related.related_model,
  733. )
  734. def create_many_related_manager(superclass, rel):
  735. """Creates a manager that subclasses 'superclass' (which is a Manager)
  736. and adds behavior for many-to-many related objects."""
  737. class ManyRelatedManager(superclass):
  738. def __init__(self, model=None, query_field_name=None, instance=None, symmetrical=None,
  739. source_field_name=None, target_field_name=None, reverse=False,
  740. through=None, prefetch_cache_name=None):
  741. super(ManyRelatedManager, self).__init__()
  742. self.model = model
  743. self.query_field_name = query_field_name
  744. source_field = through._meta.get_field(source_field_name)
  745. source_related_fields = source_field.related_fields
  746. self.core_filters = {}
  747. for lh_field, rh_field in source_related_fields:
  748. self.core_filters['%s__%s' % (query_field_name, rh_field.name)] = getattr(instance, rh_field.attname)
  749. self.instance = instance
  750. self.symmetrical = symmetrical
  751. self.source_field = source_field
  752. self.target_field = through._meta.get_field(target_field_name)
  753. self.source_field_name = source_field_name
  754. self.target_field_name = target_field_name
  755. self.reverse = reverse
  756. self.through = through
  757. self.prefetch_cache_name = prefetch_cache_name
  758. self.related_val = source_field.get_foreign_related_value(instance)
  759. if None in self.related_val:
  760. raise ValueError('"%r" needs to have a value for field "%s" before '
  761. 'this many-to-many relationship can be used.' %
  762. (instance, source_field_name))
  763. # Even if this relation is not to pk, we require still pk value.
  764. # The wish is that the instance has been already saved to DB,
  765. # although having a pk value isn't a guarantee of that.
  766. if instance.pk is None:
  767. raise ValueError("%r instance needs to have a primary key value before "
  768. "a many-to-many relationship can be used." %
  769. instance.__class__.__name__)
  770. def __call__(self, **kwargs):
  771. # We use **kwargs rather than a kwarg argument to enforce the
  772. # `manager='manager_name'` syntax.
  773. manager = getattr(self.model, kwargs.pop('manager'))
  774. manager_class = create_many_related_manager(manager.__class__, rel)
  775. return manager_class(
  776. model=self.model,
  777. query_field_name=self.query_field_name,
  778. instance=self.instance,
  779. symmetrical=self.symmetrical,
  780. source_field_name=self.source_field_name,
  781. target_field_name=self.target_field_name,
  782. reverse=self.reverse,
  783. through=self.through,
  784. prefetch_cache_name=self.prefetch_cache_name,
  785. )
  786. do_not_call_in_templates = True
  787. def _build_remove_filters(self, removed_vals):
  788. filters = Q(**{self.source_field_name: self.related_val})
  789. # No need to add a subquery condition if removed_vals is a QuerySet without
  790. # filters.
  791. removed_vals_filters = (not isinstance(removed_vals, QuerySet) or
  792. removed_vals._has_filters())
  793. if removed_vals_filters:
  794. filters &= Q(**{'%s__in' % self.target_field_name: removed_vals})
  795. if self.symmetrical:
  796. symmetrical_filters = Q(**{self.target_field_name: self.related_val})
  797. if removed_vals_filters:
  798. symmetrical_filters &= Q(
  799. **{'%s__in' % self.source_field_name: removed_vals})
  800. filters |= symmetrical_filters
  801. return filters
  802. def get_queryset(self):
  803. try:
  804. return self.instance._prefetched_objects_cache[self.prefetch_cache_name]
  805. except (AttributeError, KeyError):
  806. qs = super(ManyRelatedManager, self).get_queryset()
  807. qs._add_hints(instance=self.instance)
  808. if self._db:
  809. qs = qs.using(self._db)
  810. return qs._next_is_sticky().filter(**self.core_filters)
  811. def get_prefetch_queryset(self, instances, queryset=None):
  812. if queryset is None:
  813. queryset = super(ManyRelatedManager, self).get_queryset()
  814. queryset._add_hints(instance=instances[0])
  815. queryset = queryset.using(queryset._db or self._db)
  816. query = {'%s__in' % self.query_field_name: instances}
  817. queryset = queryset._next_is_sticky().filter(**query)
  818. # M2M: need to annotate the query in order to get the primary model
  819. # that the secondary model was actually related to. We know that
  820. # there will already be a join on the join table, so we can just add
  821. # the select.
  822. # For non-autocreated 'through' models, can't assume we are
  823. # dealing with PK values.
  824. fk = self.through._meta.get_field(self.source_field_name)
  825. join_table = self.through._meta.db_table
  826. connection = connections[queryset.db]
  827. qn = connection.ops.quote_name
  828. queryset = queryset.extra(select={
  829. '_prefetch_related_val_%s' % f.attname:
  830. '%s.%s' % (qn(join_table), qn(f.column)) for f in fk.local_related_fields})
  831. return (
  832. queryset,
  833. lambda result: tuple(
  834. getattr(result, '_prefetch_related_val_%s' % f.attname)
  835. for f in fk.local_related_fields
  836. ),
  837. lambda inst: tuple(getattr(inst, f.attname) for f in fk.foreign_related_fields),
  838. False,
  839. self.prefetch_cache_name,
  840. )
  841. def add(self, *objs):
  842. if not rel.through._meta.auto_created:
  843. opts = self.through._meta
  844. raise AttributeError(
  845. "Cannot use add() on a ManyToManyField which specifies an "
  846. "intermediary model. Use %s.%s's Manager instead." %
  847. (opts.app_label, opts.object_name)
  848. )
  849. db = router.db_for_write(self.through, instance=self.instance)
  850. with transaction.atomic(using=db, savepoint=False):
  851. self._add_items(self.source_field_name, self.target_field_name, *objs)
  852. # If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table
  853. if self.symmetrical:
  854. self._add_items(self.target_field_name, self.source_field_name, *objs)
  855. add.alters_data = True
  856. def remove(self, *objs):
  857. if not rel.through._meta.auto_created:
  858. opts = self.through._meta
  859. raise AttributeError(
  860. "Cannot use remove() on a ManyToManyField which specifies "
  861. "an intermediary model. Use %s.%s's Manager instead." %
  862. (opts.app_label, opts.object_name)
  863. )
  864. self._remove_items(self.source_field_name, self.target_field_name, *objs)
  865. remove.alters_data = True
  866. def clear(self):
  867. db = router.db_for_write(self.through, instance=self.instance)
  868. with transaction.atomic(using=db, savepoint=False):
  869. signals.m2m_changed.send(sender=self.through, action="pre_clear",
  870. instance=self.instance, reverse=self.reverse,
  871. model=self.model, pk_set=None, using=db)
  872. filters = self._build_remove_filters(super(ManyRelatedManager, self).get_queryset().using(db))
  873. self.through._default_manager.using(db).filter(filters).delete()
  874. signals.m2m_changed.send(sender=self.through, action="post_clear",
  875. instance=self.instance, reverse=self.reverse,
  876. model=self.model, pk_set=None, using=db)
  877. clear.alters_data = True
  878. def create(self, **kwargs):
  879. # This check needs to be done here, since we can't later remove this
  880. # from the method lookup table, as we do with add and remove.
  881. if not self.through._meta.auto_created:
  882. opts = self.through._meta
  883. raise AttributeError(
  884. "Cannot use create() on a ManyToManyField which specifies "
  885. "an intermediary model. Use %s.%s's Manager instead." %
  886. (opts.app_label, opts.object_name)
  887. )
  888. db = router.db_for_write(self.instance.__class__, instance=self.instance)
  889. new_obj = super(ManyRelatedManager, self.db_manager(db)).create(**kwargs)
  890. self.add(new_obj)
  891. return new_obj
  892. create.alters_data = True
  893. def get_or_create(self, **kwargs):
  894. db = router.db_for_write(self.instance.__class__, instance=self.instance)
  895. obj, created = super(ManyRelatedManager, self.db_manager(db)).get_or_create(**kwargs)
  896. # We only need to add() if created because if we got an object back
  897. # from get() then the relationship already exists.
  898. if created:
  899. self.add(obj)
  900. return obj, created
  901. get_or_create.alters_data = True
  902. def update_or_create(self, **kwargs):
  903. db = router.db_for_write(self.instance.__class__, instance=self.instance)
  904. obj, created = super(ManyRelatedManager, self.db_manager(db)).update_or_create(**kwargs)
  905. # We only need to add() if created because if we got an object back
  906. # from get() then the relationship already exists.
  907. if created:
  908. self.add(obj)
  909. return obj, created
  910. update_or_create.alters_data = True
  911. def _add_items(self, source_field_name, target_field_name, *objs):
  912. # source_field_name: the PK fieldname in join table for the source object
  913. # target_field_name: the PK fieldname in join table for the target object
  914. # *objs - objects to add. Either object instances, or primary keys of object instances.
  915. # If there aren't any objects, there is nothing to do.
  916. from django.db.models import Model
  917. if objs:
  918. new_ids = set()
  919. for obj in objs:
  920. if isinstance(obj, self.model):
  921. if not router.allow_relation(obj, self.instance):
  922. raise ValueError(
  923. 'Cannot add "%r": instance is on database "%s", value is on database "%s"' %
  924. (obj, self.instance._state.db, obj._state.db)
  925. )
  926. fk_val = self.through._meta.get_field(
  927. target_field_name).get_foreign_related_value(obj)[0]
  928. if fk_val is None:
  929. raise ValueError(
  930. 'Cannot add "%r": the value for field "%s" is None' %
  931. (obj, target_field_name)
  932. )
  933. new_ids.add(fk_val)
  934. elif isinstance(obj, Model):
  935. raise TypeError(
  936. "'%s' instance expected, got %r" %
  937. (self.model._meta.object_name, obj)
  938. )
  939. else:
  940. new_ids.add(obj)
  941. db = router.db_for_write(self.through, instance=self.instance)
  942. vals = (self.through._default_manager.using(db)
  943. .values_list(target_field_name, flat=True)
  944. .filter(**{
  945. source_field_name: self.related_val[0],
  946. '%s__in' % target_field_name: new_ids,
  947. }))
  948. new_ids = new_ids - set(vals)
  949. with transaction.atomic(using=db, savepoint=False):
  950. if self.reverse or source_field_name == self.source_field_name:
  951. # Don't send the signal when we are inserting the
  952. # duplicate data row for symmetrical reverse entries.
  953. signals.m2m_changed.send(sender=self.through, action='pre_add',
  954. instance=self.instance, reverse=self.reverse,
  955. model=self.model, pk_set=new_ids, using=db)
  956. # Add the ones that aren't there already
  957. self.through._default_manager.using(db).bulk_create([
  958. self.through(**{
  959. '%s_id' % source_field_name: self.related_val[0],
  960. '%s_id' % target_field_name: obj_id,
  961. })
  962. for obj_id in new_ids
  963. ])
  964. if self.reverse or source_field_name == self.source_field_name:
  965. # Don't send the signal when we are inserting the
  966. # duplicate data row for symmetrical reverse entries.
  967. signals.m2m_changed.send(sender=self.through, action='post_add',
  968. instance=self.instance, reverse=self.reverse,
  969. model=self.model, pk_set=new_ids, using=db)
  970. def _remove_items(self, source_field_name, target_field_name, *objs):
  971. # source_field_name: the PK colname in join table for the source object
  972. # target_field_name: the PK colname in join table for the target object
  973. # *objs - objects to remove
  974. if not objs:
  975. return
  976. # Check that all the objects are of the right type
  977. old_ids = set()
  978. for obj in objs:
  979. if isinstance(obj, self.model):
  980. fk_val = self.target_field.get_foreign_related_value(obj)[0]
  981. old_ids.add(fk_val)
  982. else:
  983. old_ids.add(obj)
  984. db = router.db_for_write(self.through, instance=self.instance)
  985. with transaction.atomic(using=db, savepoint=False):
  986. # Send a signal to the other end if need be.
  987. signals.m2m_changed.send(sender=self.through, action="pre_remove",
  988. instance=self.instance, reverse=self.reverse,
  989. model=self.model, pk_set=old_ids, using=db)
  990. target_model_qs = super(ManyRelatedManager, self).get_queryset()
  991. if target_model_qs._has_filters():
  992. old_vals = target_model_qs.using(db).filter(**{
  993. '%s__in' % self.target_field.related_field.attname: old_ids})
  994. else:
  995. old_vals = old_ids
  996. filters = self._build_remove_filters(old_vals)
  997. self.through._default_manager.using(db).filter(filters).delete()
  998. signals.m2m_changed.send(sender=self.through, action="post_remove",
  999. instance=self.instance, reverse=self.reverse,
  1000. model=self.model, pk_set=old_ids, using=db)
  1001. return ManyRelatedManager
  1002. class ManyRelatedObjectsDescriptor(object):
  1003. # This class provides the functionality that makes the related-object
  1004. # managers available as attributes on a model class, for fields that have
  1005. # multiple "remote" values and have a ManyToManyField pointed at them by
  1006. # some other model (rather than having a ManyToManyField themselves).
  1007. # In the example "publication.article_set", the article_set attribute is a
  1008. # ManyRelatedObjectsDescriptor instance.
  1009. def __init__(self, related):
  1010. self.related = related # RelatedObject instance
  1011. @cached_property
  1012. def related_manager_cls(self):
  1013. # Dynamically create a class that subclasses the related
  1014. # model's default manager.
  1015. return create_many_related_manager(
  1016. self.related.related_model._default_manager.__class__,
  1017. self.related.field.rel
  1018. )
  1019. def __get__(self, instance, instance_type=None):
  1020. if instance is None:
  1021. return self
  1022. rel_model = self.related.related_model
  1023. manager = self.related_manager_cls(
  1024. model=rel_model,
  1025. query_field_name=self.related.field.name,
  1026. prefetch_cache_name=self.related.field.related_query_name(),
  1027. instance=instance,
  1028. symmetrical=False,
  1029. source_field_name=self.related.field.m2m_reverse_field_name(),
  1030. target_field_name=self.related.field.m2m_field_name(),
  1031. reverse=True,
  1032. through=self.related.field.rel.through,
  1033. )
  1034. return manager
  1035. def __set__(self, instance, value):
  1036. if not self.related.field.rel.through._meta.auto_created:
  1037. opts = self.related.field.rel.through._meta
  1038. raise AttributeError(
  1039. "Cannot set values on a ManyToManyField which specifies an "
  1040. "intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)
  1041. )
  1042. # Force evaluation of `value` in case it's a queryset whose
  1043. # value could be affected by `manager.clear()`. Refs #19816.
  1044. value = tuple(value)
  1045. manager = self.__get__(instance)
  1046. db = router.db_for_write(manager.through, instance=manager.instance)
  1047. with transaction.atomic(using=db, savepoint=False):
  1048. manager.clear()
  1049. manager.add(*value)
  1050. class ReverseManyRelatedObjectsDescriptor(object):
  1051. # This class provides the functionality that makes the related-object
  1052. # managers available as attributes on a model class, for fields that have
  1053. # multiple "remote" values and have a ManyToManyField defined in their
  1054. # model (rather than having another model pointed *at* them).
  1055. # In the example "article.publications", the publications attribute is a
  1056. # ReverseManyRelatedObjectsDescriptor instance.
  1057. def __init__(self, m2m_field):
  1058. self.field = m2m_field
  1059. @property
  1060. def through(self):
  1061. # through is provided so that you have easy access to the through
  1062. # model (Book.authors.through) for inlines, etc. This is done as
  1063. # a property to ensure that the fully resolved value is returned.
  1064. return self.field.rel.through
  1065. @cached_property
  1066. def related_manager_cls(self):
  1067. # Dynamically create a class that subclasses the related model's
  1068. # default manager.
  1069. return create_many_related_manager(
  1070. self.field.rel.to._default_manager.__class__,
  1071. self.field.rel
  1072. )
  1073. def __get__(self, instance, instance_type=None):
  1074. if instance is None:
  1075. return self
  1076. manager = self.related_manager_cls(
  1077. model=self.field.rel.to,
  1078. query_field_name=self.field.related_query_name(),
  1079. prefetch_cache_name=self.field.name,
  1080. instance=instance,
  1081. symmetrical=self.field.rel.symmetrical,
  1082. source_field_name=self.field.m2m_field_name(),
  1083. target_field_name=self.field.m2m_reverse_field_name(),
  1084. reverse=False,
  1085. through=self.field.rel.through,
  1086. )
  1087. return manager
  1088. def __set__(self, instance, value):
  1089. if not self.field.rel.through._meta.auto_created:
  1090. opts = self.field.rel.through._meta
  1091. raise AttributeError(
  1092. "Cannot set values on a ManyToManyField which specifies an "
  1093. "intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)
  1094. )
  1095. # Force evaluation of `value` in case it's a queryset whose
  1096. # value could be affected by `manager.clear()`. Refs #19816.
  1097. value = tuple(value)
  1098. manager = self.__get__(instance)
  1099. db = router.db_for_write(manager.through, instance=manager.instance)
  1100. with transaction.atomic(using=db, savepoint=False):
  1101. manager.clear()
  1102. manager.add(*value)
  1103. class ForeignObjectRel(object):
  1104. # Field flags
  1105. auto_created = True
  1106. concrete = False
  1107. editable = False
  1108. is_relation = True
  1109. def __init__(self, field, to, related_name=None, limit_choices_to=None,
  1110. parent_link=False, on_delete=None, related_query_name=None):
  1111. self.field = field
  1112. self.to = to
  1113. self.related_name = related_name
  1114. self.related_query_name = related_query_name
  1115. self.limit_choices_to = {} if limit_choices_to is None else limit_choices_to
  1116. self.multiple = True
  1117. self.parent_link = parent_link
  1118. self.on_delete = on_delete
  1119. self.symmetrical = False
  1120. # Some of the following cached_properties can't be initialized in
  1121. # __init__ as the field doesn't have its model yet. Calling these methods
  1122. # before field.contribute_to_class() has been called will result in
  1123. # AttributeError
  1124. @cached_property
  1125. def model(self):
  1126. return self.to
  1127. @cached_property
  1128. def opts(self):
  1129. return self.related_model._meta
  1130. @cached_property
  1131. def to_opts(self):
  1132. return self.to._meta
  1133. @cached_property
  1134. def hidden(self):
  1135. return self.is_hidden()
  1136. @cached_property
  1137. def name(self):
  1138. return self.field.related_query_name()
  1139. @cached_property
  1140. def related_model(self):
  1141. if not self.field.model:
  1142. raise AttributeError(
  1143. "This property can't be accessed before self.field.contribute_to_class has been called.")
  1144. return self.field.model
  1145. @cached_property
  1146. def many_to_many(self):
  1147. return self.field.many_to_many
  1148. @cached_property
  1149. def many_to_one(self):
  1150. return self.field.one_to_many
  1151. @cached_property
  1152. def one_to_many(self):
  1153. return self.field.many_to_one
  1154. @cached_property
  1155. def one_to_one(self):
  1156. return self.field.one_to_one
  1157. def __repr__(self):
  1158. return '<%s: %s.%s>' % (type(self).__name__, self.opts.app_label, self.opts.model_name)
  1159. def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH,
  1160. limit_to_currently_related=False):
  1161. """
  1162. Returns choices with a default blank choices included, for use as
  1163. SelectField choices for this field.
  1164. Analog of django.db.models.fields.Field.get_choices(), provided
  1165. initially for utilization by RelatedFieldListFilter.
  1166. """
  1167. first_choice = blank_choice if include_blank else []
  1168. queryset = self.related_model._default_manager.all()
  1169. if limit_to_currently_related:
  1170. queryset = queryset.complex_filter(
  1171. {'%s__isnull' % self.related_model._meta.model_name: False}
  1172. )
  1173. lst = [(x._get_pk_val(), smart_text(x)) for x in queryset]
  1174. return first_choice + lst
  1175. def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
  1176. # Defer to the actual field definition for db prep
  1177. return self.field.get_db_prep_lookup(lookup_type, value, connection=connection, prepared=prepared)
  1178. def is_hidden(self):
  1179. "Should the related object be hidden?"
  1180. return self.related_name is not None and self.related_name[-1] == '+'
  1181. def get_joining_columns(self):
  1182. return self.field.get_reverse_joining_columns()
  1183. def get_extra_restriction(self, where_class, alias, related_alias):
  1184. return self.field.get_extra_restriction(where_class, related_alias, alias)
  1185. def set_field_name(self):
  1186. """
  1187. Sets the related field's name, this is not available until later stages
  1188. of app loading, so set_field_name is called from
  1189. set_attributes_from_rel()
  1190. """
  1191. # By default foreign object doesn't relate to any remote field (for
  1192. # example custom multicolumn joins currently have no remote field).
  1193. self.field_name = None
  1194. def get_lookup_constraint(self, constraint_class, alias, targets, sources, lookup_type,
  1195. raw_value):
  1196. return self.field.get_lookup_constraint(constraint_class, alias, targets, sources,
  1197. lookup_type, raw_value)
  1198. def get_accessor_name(self, model=None):
  1199. # This method encapsulates the logic that decides what name to give an
  1200. # accessor descriptor that retrieves related many-to-one or
  1201. # many-to-many objects. It uses the lower-cased object_name + "_set",
  1202. # but this can be overridden with the "related_name" option.
  1203. # Due to backwards compatibility ModelForms need to be able to provide
  1204. # an alternate model. See BaseInlineFormSet.get_default_prefix().
  1205. opts = model._meta if model else self.opts
  1206. model = model or self.related_model
  1207. if self.multiple:
  1208. # If this is a symmetrical m2m relation on self, there is no reverse accessor.
  1209. if self.symmetrical and model == self.to:
  1210. return None
  1211. if self.related_name:
  1212. return self.related_name
  1213. if opts.default_related_name:
  1214. return self.opts.default_related_name % {
  1215. 'model_name': self.opts.model_name.lower(),
  1216. 'app_label': self.opts.app_label.lower(),
  1217. }
  1218. return opts.model_name + ('_set' if self.multiple else '')
  1219. def get_cache_name(self):
  1220. return "_%s_cache" % self.get_accessor_name()
  1221. def get_path_info(self):
  1222. return self.field.get_reverse_path_info()
  1223. class ManyToOneRel(ForeignObjectRel):
  1224. def __init__(self, field, to, field_name, related_name=None, limit_choices_to=None,
  1225. parent_link=False, on_delete=None, related_query_name=None):
  1226. super(ManyToOneRel, self).__init__(
  1227. field, to, related_name=related_name, limit_choices_to=limit_choices_to,
  1228. parent_link=parent_link, on_delete=on_delete, related_query_name=related_query_name)
  1229. self.field_name = field_name
  1230. def get_related_field(self):
  1231. """
  1232. Returns the Field in the 'to' object to which this relationship is
  1233. tied.
  1234. """
  1235. field = self.to._meta.get_field(self.field_name)
  1236. if not field.concrete:
  1237. raise FieldDoesNotExist("No related field named '%s'" %
  1238. self.field_name)
  1239. return field
  1240. def set_field_name(self):
  1241. self.field_name = self.field_name or self.to._meta.pk.name
  1242. class OneToOneRel(ManyToOneRel):
  1243. def __init__(self, field, to, field_name, related_name=None, limit_choices_to=None,
  1244. parent_link=False, on_delete=None, related_query_name=None):
  1245. super(OneToOneRel, self).__init__(field, to, field_name,
  1246. related_name=related_name, limit_choices_to=limit_choices_to,
  1247. parent_link=parent_link, on_delete=on_delete, related_query_name=related_query_name)
  1248. self.multiple = False
  1249. class ManyToManyRel(ForeignObjectRel):
  1250. def __init__(self, field, to, related_name=None, limit_choices_to=None,
  1251. symmetrical=True, through=None, through_fields=None,
  1252. db_constraint=True, related_query_name=None):
  1253. if through and not db_constraint:
  1254. raise ValueError("Can't supply a through model and db_constraint=False")
  1255. if through_fields and not through:
  1256. raise ValueError("Cannot specify through_fields without a through model")
  1257. super(ManyToManyRel, self).__init__(
  1258. field, to, related_name=related_name,
  1259. limit_choices_to=limit_choices_to, related_query_name=related_query_name)
  1260. self.symmetrical = symmetrical
  1261. self.multiple = True
  1262. self.through = through
  1263. self.through_fields = through_fields
  1264. self.db_constraint = db_constraint
  1265. def is_hidden(self):
  1266. "Should the related object be hidden?"
  1267. return self.related_name is not None and self.related_name[-1] == '+'
  1268. def get_related_field(self):
  1269. """
  1270. Returns the field in the 'to' object to which this relationship is tied.
  1271. Provided for symmetry with ManyToOneRel.
  1272. """
  1273. opts = self.through._meta
  1274. if self.through_fields:
  1275. field = opts.get_field(self.through_fields[0])
  1276. else:
  1277. for field in opts.fields:
  1278. rel = getattr(field, 'rel', None)
  1279. if rel and rel.to == self.to:
  1280. break
  1281. return field.foreign_related_fields[0]
  1282. class ForeignObject(RelatedField):
  1283. # Field flags
  1284. many_to_many = False
  1285. many_to_one = False
  1286. one_to_many = True
  1287. one_to_one = False
  1288. requires_unique_target = True
  1289. related_accessor_class = ForeignRelatedObjectsDescriptor
  1290. def __init__(self, to, from_fields, to_fields, swappable=True, **kwargs):
  1291. self.from_fields = from_fields
  1292. self.to_fields = to_fields
  1293. self.swappable = swappable
  1294. if 'rel' not in kwargs:
  1295. kwargs['rel'] = ForeignObjectRel(
  1296. self, to,
  1297. related_name=kwargs.pop('related_name', None),
  1298. related_query_name=kwargs.pop('related_query_name', None),
  1299. limit_choices_to=kwargs.pop('limit_choices_to', None),
  1300. parent_link=kwargs.pop('parent_link', False),
  1301. on_delete=kwargs.pop('on_delete', CASCADE),
  1302. )
  1303. kwargs['verbose_name'] = kwargs.get('verbose_name', None)
  1304. super(ForeignObject, self).__init__(**kwargs)
  1305. def check(self, **kwargs):
  1306. errors = super(ForeignObject, self).check(**kwargs)
  1307. errors.extend(self._check_unique_target())
  1308. return errors
  1309. def _check_unique_target(self):
  1310. rel_is_string = isinstance(self.rel.to, six.string_types)
  1311. if rel_is_string or not self.requires_unique_target:
  1312. return []
  1313. # Skip if the
  1314. try:
  1315. self.foreign_related_fields
  1316. except FieldDoesNotExist:
  1317. return []
  1318. try:
  1319. self.rel
  1320. except AttributeError:
  1321. return []
  1322. has_unique_field = any(rel_field.unique
  1323. for rel_field in self.foreign_related_fields)
  1324. if not has_unique_field and len(self.foreign_related_fields) > 1:
  1325. field_combination = ', '.join("'%s'" % rel_field.name
  1326. for rel_field in self.foreign_related_fields)
  1327. model_name = self.rel.to.__name__
  1328. return [
  1329. checks.Error(
  1330. "None of the fields %s on model '%s' have a unique=True constraint."
  1331. % (field_combination, model_name),
  1332. hint=None,
  1333. obj=self,
  1334. id='fields.E310',
  1335. )
  1336. ]
  1337. elif not has_unique_field:
  1338. field_name = self.foreign_related_fields[0].name
  1339. model_name = self.rel.to.__name__
  1340. return [
  1341. checks.Error(
  1342. ("'%s.%s' must set unique=True "
  1343. "because it is referenced by a foreign key.") % (model_name, field_name),
  1344. hint=None,
  1345. obj=self,
  1346. id='fields.E311',
  1347. )
  1348. ]
  1349. else:
  1350. return []
  1351. def deconstruct(self):
  1352. name, path, args, kwargs = super(ForeignObject, self).deconstruct()
  1353. kwargs['from_fields'] = self.from_fields
  1354. kwargs['to_fields'] = self.to_fields
  1355. if self.rel.related_name is not None:
  1356. kwargs['related_name'] = self.rel.related_name
  1357. if self.rel.related_query_name is not None:
  1358. kwargs['related_query_name'] = self.rel.related_query_name
  1359. if self.rel.on_delete != CASCADE:
  1360. kwargs['on_delete'] = self.rel.on_delete
  1361. if self.rel.parent_link:
  1362. kwargs['parent_link'] = self.rel.parent_link
  1363. # Work out string form of "to"
  1364. if isinstance(self.rel.to, six.string_types):
  1365. kwargs['to'] = self.rel.to
  1366. else:
  1367. kwargs['to'] = "%s.%s" % (self.rel.to._meta.app_label, self.rel.to._meta.object_name)
  1368. # If swappable is True, then see if we're actually pointing to the target
  1369. # of a swap.
  1370. swappable_setting = self.swappable_setting
  1371. if swappable_setting is not None:
  1372. # If it's already a settings reference, error
  1373. if hasattr(kwargs['to'], "setting_name"):
  1374. if kwargs['to'].setting_name != swappable_setting:
  1375. raise ValueError(
  1376. "Cannot deconstruct a ForeignKey pointing to a model "
  1377. "that is swapped in place of more than one model (%s and %s)"
  1378. % (kwargs['to'].setting_name, swappable_setting)
  1379. )
  1380. # Set it
  1381. from django.db.migrations.writer import SettingsReference
  1382. kwargs['to'] = SettingsReference(
  1383. kwargs['to'],
  1384. swappable_setting,
  1385. )
  1386. return name, path, args, kwargs
  1387. def resolve_related_fields(self):
  1388. if len(self.from_fields) < 1 or len(self.from_fields) != len(self.to_fields):
  1389. raise ValueError('Foreign Object from and to fields must be the same non-zero length')
  1390. if isinstance(self.rel.to, six.string_types):
  1391. raise ValueError('Related model %r cannot be resolved' % self.rel.to)
  1392. related_fields = []
  1393. for index in range(len(self.from_fields)):
  1394. from_field_name = self.from_fields[index]
  1395. to_field_name = self.to_fields[index]
  1396. from_field = (self if from_field_name == 'self'
  1397. else self.opts.get_field(from_field_name))
  1398. to_field = (self.rel.to._meta.pk if to_field_name is None
  1399. else self.rel.to._meta.get_field(to_field_name))
  1400. related_fields.append((from_field, to_field))
  1401. return related_fields
  1402. @property
  1403. def related_fields(self):
  1404. if not hasattr(self, '_related_fields'):
  1405. self._related_fields = self.resolve_related_fields()
  1406. return self._related_fields
  1407. @property
  1408. def reverse_related_fields(self):
  1409. return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]
  1410. @property
  1411. def local_related_fields(self):
  1412. return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)
  1413. @property
  1414. def foreign_related_fields(self):
  1415. return tuple(rhs_field for lhs_field, rhs_field in self.related_fields)
  1416. def get_local_related_value(self, instance):
  1417. return self.get_instance_value_for_fields(instance, self.local_related_fields)
  1418. def get_foreign_related_value(self, instance):
  1419. return self.get_instance_value_for_fields(instance, self.foreign_related_fields)
  1420. @staticmethod
  1421. def get_instance_value_for_fields(instance, fields):
  1422. ret = []
  1423. opts = instance._meta
  1424. for field in fields:
  1425. # Gotcha: in some cases (like fixture loading) a model can have
  1426. # different values in parent_ptr_id and parent's id. So, use
  1427. # instance.pk (that is, parent_ptr_id) when asked for instance.id.
  1428. if field.primary_key:
  1429. possible_parent_link = opts.get_ancestor_link(field.model)
  1430. if (not possible_parent_link or
  1431. possible_parent_link.primary_key or
  1432. possible_parent_link.model._meta.abstract):
  1433. ret.append(instance.pk)
  1434. continue
  1435. ret.append(getattr(instance, field.attname))
  1436. return tuple(ret)
  1437. def get_attname_column(self):
  1438. attname, column = super(ForeignObject, self).get_attname_column()
  1439. return attname, None
  1440. def get_joining_columns(self, reverse_join=False):
  1441. source = self.reverse_related_fields if reverse_join else self.related_fields
  1442. return tuple((lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source)
  1443. def get_reverse_joining_columns(self):
  1444. return self.get_joining_columns(reverse_join=True)
  1445. def get_extra_descriptor_filter(self, instance):
  1446. """
  1447. Returns an extra filter condition for related object fetching when
  1448. user does 'instance.fieldname', that is the extra filter is used in
  1449. the descriptor of the field.
  1450. The filter should be either a dict usable in .filter(**kwargs) call or
  1451. a Q-object. The condition will be ANDed together with the relation's
  1452. joining columns.
  1453. A parallel method is get_extra_restriction() which is used in
  1454. JOIN and subquery conditions.
  1455. """
  1456. return {}
  1457. def get_extra_restriction(self, where_class, alias, related_alias):
  1458. """
  1459. Returns a pair condition used for joining and subquery pushdown. The
  1460. condition is something that responds to as_sql(compiler, connection)
  1461. method.
  1462. Note that currently referring both the 'alias' and 'related_alias'
  1463. will not work in some conditions, like subquery pushdown.
  1464. A parallel method is get_extra_descriptor_filter() which is used in
  1465. instance.fieldname related object fetching.
  1466. """
  1467. return None
  1468. def get_path_info(self):
  1469. """
  1470. Get path from this field to the related model.
  1471. """
  1472. opts = self.rel.to._meta
  1473. from_opts = self.model._meta
  1474. return [PathInfo(from_opts, opts, self.foreign_related_fields, self, False, True)]
  1475. def get_reverse_path_info(self):
  1476. """
  1477. Get path from the related model to this field's model.
  1478. """
  1479. opts = self.model._meta
  1480. from_opts = self.rel.to._meta
  1481. pathinfos = [PathInfo(from_opts, opts, (opts.pk,), self.rel, not self.unique, False)]
  1482. return pathinfos
  1483. def get_lookup_constraint(self, constraint_class, alias, targets, sources, lookups,
  1484. raw_value):
  1485. from django.db.models.sql.where import SubqueryConstraint, AND, OR
  1486. root_constraint = constraint_class()
  1487. assert len(targets) == len(sources)
  1488. if len(lookups) > 1:
  1489. raise exceptions.FieldError('Relation fields do not support nested lookups')
  1490. lookup_type = lookups[0]
  1491. def get_normalized_value(value):
  1492. from django.db.models import Model
  1493. if isinstance(value, Model):
  1494. value_list = []
  1495. for source in sources:
  1496. # Account for one-to-one relations when sent a different model
  1497. while not isinstance(value, source.model) and source.rel:
  1498. source = source.rel.to._meta.get_field(source.rel.field_name)
  1499. value_list.append(getattr(value, source.attname))
  1500. return tuple(value_list)
  1501. elif not isinstance(value, tuple):
  1502. return (value,)
  1503. return value
  1504. is_multicolumn = len(self.related_fields) > 1
  1505. if (hasattr(raw_value, '_as_sql') or
  1506. hasattr(raw_value, 'get_compiler')):
  1507. root_constraint.add(SubqueryConstraint(alias, [target.column for target in targets],
  1508. [source.name for source in sources], raw_value),
  1509. AND)
  1510. elif lookup_type == 'isnull':
  1511. root_constraint.add(IsNull(targets[0].get_col(alias, sources[0]), raw_value), AND)
  1512. elif (lookup_type == 'exact' or (lookup_type in ['gt', 'lt', 'gte', 'lte']
  1513. and not is_multicolumn)):
  1514. value = get_normalized_value(raw_value)
  1515. for target, source, val in zip(targets, sources, value):
  1516. lookup_class = target.get_lookup(lookup_type)
  1517. root_constraint.add(
  1518. lookup_class(target.get_col(alias, source), val), AND)
  1519. elif lookup_type in ['range', 'in'] and not is_multicolumn:
  1520. values = [get_normalized_value(value) for value in raw_value]
  1521. value = [val[0] for val in values]
  1522. lookup_class = targets[0].get_lookup(lookup_type)
  1523. root_constraint.add(lookup_class(targets[0].get_col(alias, sources[0]), value), AND)
  1524. elif lookup_type == 'in':
  1525. values = [get_normalized_value(value) for value in raw_value]
  1526. for value in values:
  1527. value_constraint = constraint_class()
  1528. for source, target, val in zip(sources, targets, value):
  1529. lookup_class = target.get_lookup('exact')
  1530. lookup = lookup_class(target.get_col(alias, source), val)
  1531. value_constraint.add(lookup, AND)
  1532. root_constraint.add(value_constraint, OR)
  1533. else:
  1534. raise TypeError('Related Field got invalid lookup: %s' % lookup_type)
  1535. return root_constraint
  1536. @property
  1537. def attnames(self):
  1538. return tuple(field.attname for field in self.local_related_fields)
  1539. def get_defaults(self):
  1540. return tuple(field.get_default() for field in self.local_related_fields)
  1541. def contribute_to_class(self, cls, name, virtual_only=False):
  1542. super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only)
  1543. setattr(cls, self.name, ReverseSingleRelatedObjectDescriptor(self))
  1544. def contribute_to_related_class(self, cls, related):
  1545. # Internal FK's - i.e., those with a related name ending with '+' -
  1546. # and swapped models don't get a related descriptor.
  1547. if not self.rel.is_hidden() and not related.related_model._meta.swapped:
  1548. setattr(cls, related.get_accessor_name(), self.related_accessor_class(related))
  1549. # While 'limit_choices_to' might be a callable, simply pass
  1550. # it along for later - this is too early because it's still
  1551. # model load time.
  1552. if self.rel.limit_choices_to:
  1553. cls._meta.related_fkey_lookups.append(self.rel.limit_choices_to)
  1554. class ForeignKey(ForeignObject):
  1555. # Field flags
  1556. many_to_many = False
  1557. many_to_one = False
  1558. one_to_many = True
  1559. one_to_one = False
  1560. empty_strings_allowed = False
  1561. default_error_messages = {
  1562. 'invalid': _('%(model)s instance with %(field)s %(value)r does not exist.')
  1563. }
  1564. description = _("Foreign Key (type determined by related field)")
  1565. def __init__(self, to, to_field=None, rel_class=ManyToOneRel,
  1566. db_constraint=True, **kwargs):
  1567. try:
  1568. to._meta.model_name
  1569. except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT
  1570. assert isinstance(to, six.string_types), (
  1571. "%s(%r) is invalid. First parameter to ForeignKey must be "
  1572. "either a model, a model name, or the string %r" % (
  1573. self.__class__.__name__, to,
  1574. RECURSIVE_RELATIONSHIP_CONSTANT,
  1575. )
  1576. )
  1577. else:
  1578. # For backwards compatibility purposes, we need to *try* and set
  1579. # the to_field during FK construction. It won't be guaranteed to
  1580. # be correct until contribute_to_class is called. Refs #12190.
  1581. to_field = to_field or (to._meta.pk and to._meta.pk.name)
  1582. if 'db_index' not in kwargs:
  1583. kwargs['db_index'] = True
  1584. self.db_constraint = db_constraint
  1585. kwargs['rel'] = rel_class(
  1586. self, to, to_field,
  1587. related_name=kwargs.pop('related_name', None),
  1588. related_query_name=kwargs.pop('related_query_name', None),
  1589. limit_choices_to=kwargs.pop('limit_choices_to', None),
  1590. parent_link=kwargs.pop('parent_link', False),
  1591. on_delete=kwargs.pop('on_delete', CASCADE),
  1592. )
  1593. super(ForeignKey, self).__init__(to, ['self'], [to_field], **kwargs)
  1594. def check(self, **kwargs):
  1595. errors = super(ForeignKey, self).check(**kwargs)
  1596. errors.extend(self._check_on_delete())
  1597. errors.extend(self._check_unique())
  1598. return errors
  1599. def _check_on_delete(self):
  1600. on_delete = getattr(self.rel, 'on_delete', None)
  1601. if on_delete == SET_NULL and not self.null:
  1602. return [
  1603. checks.Error(
  1604. 'Field specifies on_delete=SET_NULL, but cannot be null.',
  1605. hint='Set null=True argument on the field, or change the on_delete rule.',
  1606. obj=self,
  1607. id='fields.E320',
  1608. )
  1609. ]
  1610. elif on_delete == SET_DEFAULT and not self.has_default():
  1611. return [
  1612. checks.Error(
  1613. 'Field specifies on_delete=SET_DEFAULT, but has no default value.',
  1614. hint='Set a default value, or change the on_delete rule.',
  1615. obj=self,
  1616. id='fields.E321',
  1617. )
  1618. ]
  1619. else:
  1620. return []
  1621. def _check_unique(self, **kwargs):
  1622. return [
  1623. checks.Warning(
  1624. 'Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.',
  1625. hint='ForeignKey(unique=True) is usually better served by a OneToOneField.',
  1626. obj=self,
  1627. id='fields.W342',
  1628. )
  1629. ] if self.unique else []
  1630. def deconstruct(self):
  1631. name, path, args, kwargs = super(ForeignKey, self).deconstruct()
  1632. del kwargs['to_fields']
  1633. del kwargs['from_fields']
  1634. # Handle the simpler arguments
  1635. if self.db_index:
  1636. del kwargs['db_index']
  1637. else:
  1638. kwargs['db_index'] = False
  1639. if self.db_constraint is not True:
  1640. kwargs['db_constraint'] = self.db_constraint
  1641. # Rel needs more work.
  1642. to_meta = getattr(self.rel.to, "_meta", None)
  1643. if self.rel.field_name and (not to_meta or (to_meta.pk and self.rel.field_name != to_meta.pk.name)):
  1644. kwargs['to_field'] = self.rel.field_name
  1645. return name, path, args, kwargs
  1646. @property
  1647. def related_field(self):
  1648. return self.foreign_related_fields[0]
  1649. def get_reverse_path_info(self):
  1650. """
  1651. Get path from the related model to this field's model.
  1652. """
  1653. opts = self.model._meta
  1654. from_opts = self.rel.to._meta
  1655. pathinfos = [PathInfo(from_opts, opts, (opts.pk,), self.rel, not self.unique, False)]
  1656. return pathinfos
  1657. def validate(self, value, model_instance):
  1658. if self.rel.parent_link:
  1659. return
  1660. super(ForeignKey, self).validate(value, model_instance)
  1661. if value is None:
  1662. return
  1663. using = router.db_for_read(model_instance.__class__, instance=model_instance)
  1664. qs = self.rel.to._default_manager.using(using).filter(
  1665. **{self.rel.field_name: value}
  1666. )
  1667. qs = qs.complex_filter(self.get_limit_choices_to())
  1668. if not qs.exists():
  1669. raise exceptions.ValidationError(
  1670. self.error_messages['invalid'],
  1671. code='invalid',
  1672. params={
  1673. 'model': self.rel.to._meta.verbose_name, 'pk': value,
  1674. 'field': self.rel.field_name, 'value': value,
  1675. }, # 'pk' is included for backwards compatibility
  1676. )
  1677. def get_attname(self):
  1678. return '%s_id' % self.name
  1679. def get_attname_column(self):
  1680. attname = self.get_attname()
  1681. column = self.db_column or attname
  1682. return attname, column
  1683. def get_default(self):
  1684. "Here we check if the default value is an object and return the to_field if so."
  1685. field_default = super(ForeignKey, self).get_default()
  1686. if isinstance(field_default, self.rel.to):
  1687. return getattr(field_default, self.related_field.attname)
  1688. return field_default
  1689. def get_db_prep_save(self, value, connection):
  1690. if value is None or (value == '' and
  1691. (not self.related_field.empty_strings_allowed or
  1692. connection.features.interprets_empty_strings_as_nulls)):
  1693. return None
  1694. else:
  1695. return self.related_field.get_db_prep_save(value, connection=connection)
  1696. def value_to_string(self, obj):
  1697. if not obj:
  1698. # In required many-to-one fields with only one available choice,
  1699. # select that one available choice. Note: For SelectFields
  1700. # we have to check that the length of choices is *2*, not 1,
  1701. # because SelectFields always have an initial "blank" value.
  1702. if not self.blank and self.choices:
  1703. choice_list = self.get_choices_default()
  1704. if len(choice_list) == 2:
  1705. return smart_text(choice_list[1][0])
  1706. return super(ForeignKey, self).value_to_string(obj)
  1707. def contribute_to_related_class(self, cls, related):
  1708. super(ForeignKey, self).contribute_to_related_class(cls, related)
  1709. if self.rel.field_name is None:
  1710. self.rel.field_name = cls._meta.pk.name
  1711. def formfield(self, **kwargs):
  1712. db = kwargs.pop('using', None)
  1713. if isinstance(self.rel.to, six.string_types):
  1714. raise ValueError("Cannot create form field for %r yet, because "
  1715. "its related model %r has not been loaded yet" %
  1716. (self.name, self.rel.to))
  1717. defaults = {
  1718. 'form_class': forms.ModelChoiceField,
  1719. 'queryset': self.rel.to._default_manager.using(db),
  1720. 'to_field_name': self.rel.field_name,
  1721. }
  1722. defaults.update(kwargs)
  1723. return super(ForeignKey, self).formfield(**defaults)
  1724. def db_type(self, connection):
  1725. # The database column type of a ForeignKey is the column type
  1726. # of the field to which it points. An exception is if the ForeignKey
  1727. # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField,
  1728. # in which case the column type is simply that of an IntegerField.
  1729. # If the database needs similar types for key fields however, the only
  1730. # thing we can do is making AutoField an IntegerField.
  1731. rel_field = self.related_field
  1732. if (isinstance(rel_field, AutoField) or
  1733. (not connection.features.related_fields_match_type and
  1734. isinstance(rel_field, (PositiveIntegerField,
  1735. PositiveSmallIntegerField)))):
  1736. return IntegerField().db_type(connection=connection)
  1737. return rel_field.db_type(connection=connection)
  1738. def db_parameters(self, connection):
  1739. return {"type": self.db_type(connection), "check": []}
  1740. class OneToOneField(ForeignKey):
  1741. """
  1742. A OneToOneField is essentially the same as a ForeignKey, with the exception
  1743. that always carries a "unique" constraint with it and the reverse relation
  1744. always returns the object pointed to (since there will only ever be one),
  1745. rather than returning a list.
  1746. """
  1747. # Field flags
  1748. many_to_many = False
  1749. many_to_one = False
  1750. one_to_many = False
  1751. one_to_one = True
  1752. related_accessor_class = SingleRelatedObjectDescriptor
  1753. description = _("One-to-one relationship")
  1754. def __init__(self, to, to_field=None, **kwargs):
  1755. kwargs['unique'] = True
  1756. super(OneToOneField, self).__init__(to, to_field, OneToOneRel, **kwargs)
  1757. def deconstruct(self):
  1758. name, path, args, kwargs = super(OneToOneField, self).deconstruct()
  1759. if "unique" in kwargs:
  1760. del kwargs['unique']
  1761. return name, path, args, kwargs
  1762. def formfield(self, **kwargs):
  1763. if self.rel.parent_link:
  1764. return None
  1765. return super(OneToOneField, self).formfield(**kwargs)
  1766. def save_form_data(self, instance, data):
  1767. if isinstance(data, self.rel.to):
  1768. setattr(instance, self.name, data)
  1769. else:
  1770. setattr(instance, self.attname, data)
  1771. def _check_unique(self, **kwargs):
  1772. # override ForeignKey since check isn't applicable here
  1773. return []
  1774. def create_many_to_many_intermediary_model(field, klass):
  1775. from django.db import models
  1776. managed = True
  1777. if isinstance(field.rel.to, six.string_types) and field.rel.to != RECURSIVE_RELATIONSHIP_CONSTANT:
  1778. to_model = field.rel.to
  1779. to = to_model.split('.')[-1]
  1780. def set_managed(field, model, cls):
  1781. field.rel.through._meta.managed = model._meta.managed or cls._meta.managed
  1782. add_lazy_relation(klass, field, to_model, set_managed)
  1783. elif isinstance(field.rel.to, six.string_types):
  1784. to = klass._meta.object_name
  1785. to_model = klass
  1786. managed = klass._meta.managed
  1787. else:
  1788. to = field.rel.to._meta.object_name
  1789. to_model = field.rel.to
  1790. managed = klass._meta.managed or to_model._meta.managed
  1791. name = '%s_%s' % (klass._meta.object_name, field.name)
  1792. if field.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to == klass._meta.object_name:
  1793. from_ = 'from_%s' % to.lower()
  1794. to = 'to_%s' % to.lower()
  1795. else:
  1796. from_ = klass._meta.model_name
  1797. to = to.lower()
  1798. meta = type(str('Meta'), (object,), {
  1799. 'db_table': field._get_m2m_db_table(klass._meta),
  1800. 'managed': managed,
  1801. 'auto_created': klass,
  1802. 'app_label': klass._meta.app_label,
  1803. 'db_tablespace': klass._meta.db_tablespace,
  1804. 'unique_together': (from_, to),
  1805. 'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to},
  1806. 'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to},
  1807. 'apps': field.model._meta.apps,
  1808. })
  1809. # Construct and return the new class.
  1810. return type(str(name), (models.Model,), {
  1811. 'Meta': meta,
  1812. '__module__': klass.__module__,
  1813. from_: models.ForeignKey(
  1814. klass,
  1815. related_name='%s+' % name,
  1816. db_tablespace=field.db_tablespace,
  1817. db_constraint=field.rel.db_constraint,
  1818. ),
  1819. to: models.ForeignKey(
  1820. to_model,
  1821. related_name='%s+' % name,
  1822. db_tablespace=field.db_tablespace,
  1823. db_constraint=field.rel.db_constraint,
  1824. )
  1825. })
  1826. class ManyToManyField(RelatedField):
  1827. # Field flags
  1828. many_to_many = True
  1829. many_to_one = False
  1830. one_to_many = False
  1831. one_to_one = False
  1832. description = _("Many-to-many relationship")
  1833. def __init__(self, to, db_constraint=True, swappable=True, **kwargs):
  1834. try:
  1835. to._meta
  1836. except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT
  1837. assert isinstance(to, six.string_types), (
  1838. "%s(%r) is invalid. First parameter to ManyToManyField must be "
  1839. "either a model, a model name, or the string %r" %
  1840. (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
  1841. )
  1842. # Class names must be ASCII in Python 2.x, so we forcibly coerce it
  1843. # here to break early if there's a problem.
  1844. to = str(to)
  1845. kwargs['verbose_name'] = kwargs.get('verbose_name', None)
  1846. kwargs['rel'] = ManyToManyRel(
  1847. self, to,
  1848. related_name=kwargs.pop('related_name', None),
  1849. related_query_name=kwargs.pop('related_query_name', None),
  1850. limit_choices_to=kwargs.pop('limit_choices_to', None),
  1851. symmetrical=kwargs.pop('symmetrical', to == RECURSIVE_RELATIONSHIP_CONSTANT),
  1852. through=kwargs.pop('through', None),
  1853. through_fields=kwargs.pop('through_fields', None),
  1854. db_constraint=db_constraint,
  1855. )
  1856. self.swappable = swappable
  1857. self.db_table = kwargs.pop('db_table', None)
  1858. if kwargs['rel'].through is not None:
  1859. assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used."
  1860. super(ManyToManyField, self).__init__(**kwargs)
  1861. def check(self, **kwargs):
  1862. errors = super(ManyToManyField, self).check(**kwargs)
  1863. errors.extend(self._check_unique(**kwargs))
  1864. errors.extend(self._check_relationship_model(**kwargs))
  1865. errors.extend(self._check_ignored_options(**kwargs))
  1866. return errors
  1867. def _check_unique(self, **kwargs):
  1868. if self.unique:
  1869. return [
  1870. checks.Error(
  1871. 'ManyToManyFields cannot be unique.',
  1872. hint=None,
  1873. obj=self,
  1874. id='fields.E330',
  1875. )
  1876. ]
  1877. return []
  1878. def _check_ignored_options(self, **kwargs):
  1879. warnings = []
  1880. if self.null:
  1881. warnings.append(
  1882. checks.Warning(
  1883. 'null has no effect on ManyToManyField.',
  1884. hint=None,
  1885. obj=self,
  1886. id='fields.W340',
  1887. )
  1888. )
  1889. if len(self._validators) > 0:
  1890. warnings.append(
  1891. checks.Warning(
  1892. 'ManyToManyField does not support validators.',
  1893. hint=None,
  1894. obj=self,
  1895. id='fields.W341',
  1896. )
  1897. )
  1898. return warnings
  1899. def _check_relationship_model(self, from_model=None, **kwargs):
  1900. if hasattr(self.rel.through, '_meta'):
  1901. qualified_model_name = "%s.%s" % (
  1902. self.rel.through._meta.app_label, self.rel.through.__name__)
  1903. else:
  1904. qualified_model_name = self.rel.through
  1905. errors = []
  1906. if self.rel.through not in apps.get_models(include_auto_created=True):
  1907. # The relationship model is not installed.
  1908. errors.append(
  1909. checks.Error(
  1910. ("Field specifies a many-to-many relation through model "
  1911. "'%s', which has not been installed.") %
  1912. qualified_model_name,
  1913. hint=None,
  1914. obj=self,
  1915. id='fields.E331',
  1916. )
  1917. )
  1918. else:
  1919. assert from_model is not None, \
  1920. "ManyToManyField with intermediate " \
  1921. "tables cannot be checked if you don't pass the model " \
  1922. "where the field is attached to."
  1923. # Set some useful local variables
  1924. to_model = self.rel.to
  1925. from_model_name = from_model._meta.object_name
  1926. if isinstance(to_model, six.string_types):
  1927. to_model_name = to_model
  1928. else:
  1929. to_model_name = to_model._meta.object_name
  1930. relationship_model_name = self.rel.through._meta.object_name
  1931. self_referential = from_model == to_model
  1932. # Check symmetrical attribute.
  1933. if (self_referential and self.rel.symmetrical and
  1934. not self.rel.through._meta.auto_created):
  1935. errors.append(
  1936. checks.Error(
  1937. 'Many-to-many fields with intermediate tables must not be symmetrical.',
  1938. hint=None,
  1939. obj=self,
  1940. id='fields.E332',
  1941. )
  1942. )
  1943. # Count foreign keys in intermediate model
  1944. if self_referential:
  1945. seen_self = sum(from_model == getattr(field.rel, 'to', None)
  1946. for field in self.rel.through._meta.fields)
  1947. if seen_self > 2 and not self.rel.through_fields:
  1948. errors.append(
  1949. checks.Error(
  1950. ("The model is used as an intermediate model by "
  1951. "'%s', but it has more than two foreign keys "
  1952. "to '%s', which is ambiguous. You must specify "
  1953. "which two foreign keys Django should use via the "
  1954. "through_fields keyword argument.") % (self, from_model_name),
  1955. hint=("Use through_fields to specify which two "
  1956. "foreign keys Django should use."),
  1957. obj=self.rel.through,
  1958. id='fields.E333',
  1959. )
  1960. )
  1961. else:
  1962. # Count foreign keys in relationship model
  1963. seen_from = sum(from_model == getattr(field.rel, 'to', None)
  1964. for field in self.rel.through._meta.fields)
  1965. seen_to = sum(to_model == getattr(field.rel, 'to', None)
  1966. for field in self.rel.through._meta.fields)
  1967. if seen_from > 1 and not self.rel.through_fields:
  1968. errors.append(
  1969. checks.Error(
  1970. ("The model is used as an intermediate model by "
  1971. "'%s', but it has more than one foreign key "
  1972. "from '%s', which is ambiguous. You must specify "
  1973. "which foreign key Django should use via the "
  1974. "through_fields keyword argument.") % (self, from_model_name),
  1975. hint=('If you want to create a recursive relationship, '
  1976. 'use ForeignKey("self", symmetrical=False, '
  1977. 'through="%s").') % relationship_model_name,
  1978. obj=self,
  1979. id='fields.E334',
  1980. )
  1981. )
  1982. if seen_to > 1 and not self.rel.through_fields:
  1983. errors.append(
  1984. checks.Error(
  1985. ("The model is used as an intermediate model by "
  1986. "'%s', but it has more than one foreign key "
  1987. "to '%s', which is ambiguous. You must specify "
  1988. "which foreign key Django should use via the "
  1989. "through_fields keyword argument.") % (self, to_model_name),
  1990. hint=('If you want to create a recursive '
  1991. 'relationship, use ForeignKey("self", '
  1992. 'symmetrical=False, through="%s").') % relationship_model_name,
  1993. obj=self,
  1994. id='fields.E335',
  1995. )
  1996. )
  1997. if seen_from == 0 or seen_to == 0:
  1998. errors.append(
  1999. checks.Error(
  2000. ("The model is used as an intermediate model by "
  2001. "'%s', but it does not have a foreign key to '%s' or '%s'.") % (
  2002. self, from_model_name, to_model_name
  2003. ),
  2004. hint=None,
  2005. obj=self.rel.through,
  2006. id='fields.E336',
  2007. )
  2008. )
  2009. # Validate `through_fields`
  2010. if self.rel.through_fields is not None:
  2011. # Validate that we're given an iterable of at least two items
  2012. # and that none of them is "falsy"
  2013. if not (len(self.rel.through_fields) >= 2 and
  2014. self.rel.through_fields[0] and self.rel.through_fields[1]):
  2015. errors.append(
  2016. checks.Error(
  2017. ("Field specifies 'through_fields' but does not "
  2018. "provide the names of the two link fields that should be "
  2019. "used for the relation through model "
  2020. "'%s'.") % qualified_model_name,
  2021. hint=("Make sure you specify 'through_fields' as "
  2022. "through_fields=('field1', 'field2')"),
  2023. obj=self,
  2024. id='fields.E337',
  2025. )
  2026. )
  2027. # Validate the given through fields -- they should be actual
  2028. # fields on the through model, and also be foreign keys to the
  2029. # expected models
  2030. else:
  2031. assert from_model is not None, \
  2032. "ManyToManyField with intermediate " \
  2033. "tables cannot be checked if you don't pass the model " \
  2034. "where the field is attached to."
  2035. source, through, target = from_model, self.rel.through, self.rel.to
  2036. source_field_name, target_field_name = self.rel.through_fields[:2]
  2037. for field_name, related_model in ((source_field_name, source),
  2038. (target_field_name, target)):
  2039. possible_field_names = []
  2040. for f in through._meta.fields:
  2041. if hasattr(f, 'rel') and getattr(f.rel, 'to', None) == related_model:
  2042. possible_field_names.append(f.name)
  2043. if possible_field_names:
  2044. hint = ("Did you mean one of the following foreign "
  2045. "keys to '%s': %s?") % (related_model._meta.object_name,
  2046. ', '.join(possible_field_names))
  2047. else:
  2048. hint = None
  2049. try:
  2050. field = through._meta.get_field(field_name)
  2051. except FieldDoesNotExist:
  2052. errors.append(
  2053. checks.Error(
  2054. ("The intermediary model '%s' has no field '%s'.") % (
  2055. qualified_model_name, field_name),
  2056. hint=hint,
  2057. obj=self,
  2058. id='fields.E338',
  2059. )
  2060. )
  2061. else:
  2062. if not (hasattr(field, 'rel') and
  2063. getattr(field.rel, 'to', None) == related_model):
  2064. errors.append(
  2065. checks.Error(
  2066. "'%s.%s' is not a foreign key to '%s'." % (
  2067. through._meta.object_name, field_name,
  2068. related_model._meta.object_name),
  2069. hint=hint,
  2070. obj=self,
  2071. id='fields.E339',
  2072. )
  2073. )
  2074. return errors
  2075. def deconstruct(self):
  2076. name, path, args, kwargs = super(ManyToManyField, self).deconstruct()
  2077. # Handle the simpler arguments
  2078. if self.db_table is not None:
  2079. kwargs['db_table'] = self.db_table
  2080. if self.rel.db_constraint is not True:
  2081. kwargs['db_constraint'] = self.rel.db_constraint
  2082. if self.rel.related_name is not None:
  2083. kwargs['related_name'] = self.rel.related_name
  2084. if self.rel.related_query_name is not None:
  2085. kwargs['related_query_name'] = self.rel.related_query_name
  2086. # Rel needs more work.
  2087. if isinstance(self.rel.to, six.string_types):
  2088. kwargs['to'] = self.rel.to
  2089. else:
  2090. kwargs['to'] = "%s.%s" % (self.rel.to._meta.app_label, self.rel.to._meta.object_name)
  2091. if getattr(self.rel, 'through', None) is not None:
  2092. if isinstance(self.rel.through, six.string_types):
  2093. kwargs['through'] = self.rel.through
  2094. elif not self.rel.through._meta.auto_created:
  2095. kwargs['through'] = "%s.%s" % (self.rel.through._meta.app_label, self.rel.through._meta.object_name)
  2096. # If swappable is True, then see if we're actually pointing to the target
  2097. # of a swap.
  2098. swappable_setting = self.swappable_setting
  2099. if swappable_setting is not None:
  2100. # If it's already a settings reference, error
  2101. if hasattr(kwargs['to'], "setting_name"):
  2102. if kwargs['to'].setting_name != swappable_setting:
  2103. raise ValueError(
  2104. "Cannot deconstruct a ManyToManyField pointing to a "
  2105. "model that is swapped in place of more than one model "
  2106. "(%s and %s)" % (kwargs['to'].setting_name, swappable_setting)
  2107. )
  2108. # Set it
  2109. from django.db.migrations.writer import SettingsReference
  2110. kwargs['to'] = SettingsReference(
  2111. kwargs['to'],
  2112. swappable_setting,
  2113. )
  2114. return name, path, args, kwargs
  2115. def _get_path_info(self, direct=False):
  2116. """
  2117. Called by both direct and indirect m2m traversal.
  2118. """
  2119. pathinfos = []
  2120. int_model = self.rel.through
  2121. linkfield1 = int_model._meta.get_field(self.m2m_field_name())
  2122. linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name())
  2123. if direct:
  2124. join1infos = linkfield1.get_reverse_path_info()
  2125. join2infos = linkfield2.get_path_info()
  2126. else:
  2127. join1infos = linkfield2.get_reverse_path_info()
  2128. join2infos = linkfield1.get_path_info()
  2129. pathinfos.extend(join1infos)
  2130. pathinfos.extend(join2infos)
  2131. return pathinfos
  2132. def get_path_info(self):
  2133. return self._get_path_info(direct=True)
  2134. def get_reverse_path_info(self):
  2135. return self._get_path_info(direct=False)
  2136. def get_choices_default(self):
  2137. return Field.get_choices(self, include_blank=False)
  2138. def _get_m2m_db_table(self, opts):
  2139. "Function that can be curried to provide the m2m table name for this relation"
  2140. if self.rel.through is not None:
  2141. return self.rel.through._meta.db_table
  2142. elif self.db_table:
  2143. return self.db_table
  2144. else:
  2145. return utils.truncate_name('%s_%s' % (opts.db_table, self.name),
  2146. connection.ops.max_name_length())
  2147. def _get_m2m_attr(self, related, attr):
  2148. "Function that can be curried to provide the source accessor or DB column name for the m2m table"
  2149. cache_attr = '_m2m_%s_cache' % attr
  2150. if hasattr(self, cache_attr):
  2151. return getattr(self, cache_attr)
  2152. if self.rel.through_fields is not None:
  2153. link_field_name = self.rel.through_fields[0]
  2154. else:
  2155. link_field_name = None
  2156. for f in self.rel.through._meta.fields:
  2157. if (f.is_relation and f.rel.to == related.related_model and
  2158. (link_field_name is None or link_field_name == f.name)):
  2159. setattr(self, cache_attr, getattr(f, attr))
  2160. return getattr(self, cache_attr)
  2161. def _get_m2m_reverse_attr(self, related, attr):
  2162. "Function that can be curried to provide the related accessor or DB column name for the m2m table"
  2163. cache_attr = '_m2m_reverse_%s_cache' % attr
  2164. if hasattr(self, cache_attr):
  2165. return getattr(self, cache_attr)
  2166. found = False
  2167. if self.rel.through_fields is not None:
  2168. link_field_name = self.rel.through_fields[1]
  2169. else:
  2170. link_field_name = None
  2171. for f in self.rel.through._meta.fields:
  2172. # NOTE f.rel.to != f.related_model
  2173. if f.is_relation and f.rel.to == related.model:
  2174. if link_field_name is None and related.related_model == related.model:
  2175. # If this is an m2m-intermediate to self,
  2176. # the first foreign key you find will be
  2177. # the source column. Keep searching for
  2178. # the second foreign key.
  2179. if found:
  2180. setattr(self, cache_attr, getattr(f, attr))
  2181. break
  2182. else:
  2183. found = True
  2184. elif link_field_name is None or link_field_name == f.name:
  2185. setattr(self, cache_attr, getattr(f, attr))
  2186. break
  2187. return getattr(self, cache_attr)
  2188. def value_to_string(self, obj):
  2189. data = ''
  2190. if obj:
  2191. qs = getattr(obj, self.name).all()
  2192. data = [instance._get_pk_val() for instance in qs]
  2193. else:
  2194. # In required many-to-many fields with only one available choice,
  2195. # select that one available choice.
  2196. if not self.blank:
  2197. choices_list = self.get_choices_default()
  2198. if len(choices_list) == 1:
  2199. data = [choices_list[0][0]]
  2200. return smart_text(data)
  2201. def contribute_to_class(self, cls, name, **kwargs):
  2202. # To support multiple relations to self, it's useful to have a non-None
  2203. # related name on symmetrical relations for internal reasons. The
  2204. # concept doesn't make a lot of sense externally ("you want me to
  2205. # specify *what* on my non-reversible relation?!"), so we set it up
  2206. # automatically. The funky name reduces the chance of an accidental
  2207. # clash.
  2208. if self.rel.symmetrical and (self.rel.to == "self" or self.rel.to == cls._meta.object_name):
  2209. self.rel.related_name = "%s_rel_+" % name
  2210. super(ManyToManyField, self).contribute_to_class(cls, name, **kwargs)
  2211. # The intermediate m2m model is not auto created if:
  2212. # 1) There is a manually specified intermediate, or
  2213. # 2) The class owning the m2m field is abstract.
  2214. # 3) The class owning the m2m field has been swapped out.
  2215. if not self.rel.through and not cls._meta.abstract and not cls._meta.swapped:
  2216. self.rel.through = create_many_to_many_intermediary_model(self, cls)
  2217. # Add the descriptor for the m2m relation
  2218. setattr(cls, self.name, ReverseManyRelatedObjectsDescriptor(self))
  2219. # Set up the accessor for the m2m table name for the relation
  2220. self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta)
  2221. # Populate some necessary rel arguments so that cross-app relations
  2222. # work correctly.
  2223. if isinstance(self.rel.through, six.string_types):
  2224. def resolve_through_model(field, model, cls):
  2225. field.rel.through = model
  2226. add_lazy_relation(cls, self, self.rel.through, resolve_through_model)
  2227. def contribute_to_related_class(self, cls, related):
  2228. # Internal M2Ms (i.e., those with a related name ending with '+')
  2229. # and swapped models don't get a related descriptor.
  2230. if not self.rel.is_hidden() and not related.related_model._meta.swapped:
  2231. setattr(cls, related.get_accessor_name(), ManyRelatedObjectsDescriptor(related))
  2232. # Set up the accessors for the column names on the m2m table
  2233. self.m2m_column_name = curry(self._get_m2m_attr, related, 'column')
  2234. self.m2m_reverse_name = curry(self._get_m2m_reverse_attr, related, 'column')
  2235. self.m2m_field_name = curry(self._get_m2m_attr, related, 'name')
  2236. self.m2m_reverse_field_name = curry(self._get_m2m_reverse_attr, related, 'name')
  2237. get_m2m_rel = curry(self._get_m2m_attr, related, 'rel')
  2238. self.m2m_target_field_name = lambda: get_m2m_rel().field_name
  2239. get_m2m_reverse_rel = curry(self._get_m2m_reverse_attr, related, 'rel')
  2240. self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name
  2241. def set_attributes_from_rel(self):
  2242. pass
  2243. def value_from_object(self, obj):
  2244. "Returns the value of this field in the given model instance."
  2245. return getattr(obj, self.attname).all()
  2246. def save_form_data(self, instance, data):
  2247. setattr(instance, self.attname, data)
  2248. def formfield(self, **kwargs):
  2249. db = kwargs.pop('using', None)
  2250. defaults = {
  2251. 'form_class': forms.ModelMultipleChoiceField,
  2252. 'queryset': self.rel.to._default_manager.using(db),
  2253. }
  2254. defaults.update(kwargs)
  2255. # If initial is passed in, it's a list of related objects, but the
  2256. # MultipleChoiceField takes a list of IDs.
  2257. if defaults.get('initial') is not None:
  2258. initial = defaults['initial']
  2259. if callable(initial):
  2260. initial = initial()
  2261. defaults['initial'] = [i._get_pk_val() for i in initial]
  2262. return super(ManyToManyField, self).formfield(**defaults)
  2263. def db_type(self, connection):
  2264. # A ManyToManyField is not represented by a single column,
  2265. # so return None.
  2266. return None
  2267. def db_parameters(self, connection):
  2268. return {"type": None, "check": None}