related.py 106 KB

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