related.py 102 KB

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