related_descriptors.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. """
  2. Accessors for related objects.
  3. When a field defines a relation between two models, each model class provides
  4. an attribute to access related instances of the other model class (unless the
  5. reverse accessor has been disabled with related_name='+').
  6. Accessors are implemented as descriptors in order to customize access and
  7. assignment. This module defines the descriptor classes.
  8. Forward accessors follow foreign keys. Reverse accessors trace them back. For
  9. example, with the following models::
  10. class Parent(Model):
  11. pass
  12. class Child(Model):
  13. parent = ForeignKey(Parent, related_name='children')
  14. ``child.parent`` is a forward many-to-one relation. ``parent.children`` is a
  15. reverse many-to-one relation.
  16. There are three types of relations (many-to-one, one-to-one, and many-to-many)
  17. and two directions (forward and reverse) for a total of six combinations.
  18. 1. Related instance on the forward side of a many-to-one relation:
  19. ``ForwardManyToOneDescriptor``.
  20. Uniqueness of foreign key values is irrelevant to accessing the related
  21. instance, making the many-to-one and one-to-one cases identical as far as
  22. the descriptor is concerned. The constraint is checked upstream (unicity
  23. validation in forms) or downstream (unique indexes in the database).
  24. 2. Related instance on the forward side of a one-to-one
  25. relation: ``ForwardOneToOneDescriptor``.
  26. It avoids querying the database when accessing the parent link field in
  27. a multi-table inheritance scenario.
  28. 3. Related instance on the reverse side of a one-to-one relation:
  29. ``ReverseOneToOneDescriptor``.
  30. One-to-one relations are asymmetrical, despite the apparent symmetry of the
  31. name, because they're implemented in the database with a foreign key from
  32. one table to another. As a consequence ``ReverseOneToOneDescriptor`` is
  33. slightly different from ``ForwardManyToOneDescriptor``.
  34. 4. Related objects manager for related instances on the reverse side of a
  35. many-to-one relation: ``ReverseManyToOneDescriptor``.
  36. Unlike the previous two classes, this one provides access to a collection
  37. of objects. It returns a manager rather than an instance.
  38. 5. Related objects manager for related instances on the forward or reverse
  39. sides of a many-to-many relation: ``ManyToManyDescriptor``.
  40. Many-to-many relations are symmetrical. The syntax of Django models
  41. requires declaring them on one side but that's an implementation detail.
  42. They could be declared on the other side without any change in behavior.
  43. Therefore the forward and reverse descriptors can be the same.
  44. If you're looking for ``ForwardManyToManyDescriptor`` or
  45. ``ReverseManyToManyDescriptor``, use ``ManyToManyDescriptor`` instead.
  46. """
  47. from operator import attrgetter
  48. from django.db import connections, router, transaction
  49. from django.db.models import Q, signals
  50. from django.db.models.query import QuerySet
  51. from django.utils.functional import cached_property
  52. class ForwardManyToOneDescriptor:
  53. """
  54. Accessor to the related object on the forward side of a many-to-one or
  55. one-to-one (via ForwardOneToOneDescriptor subclass) relation.
  56. In the example::
  57. class Child(Model):
  58. parent = ForeignKey(Parent, related_name='children')
  59. ``child.parent`` is a ``ForwardManyToOneDescriptor`` instance.
  60. """
  61. def __init__(self, field_with_rel):
  62. self.field = field_with_rel
  63. self.cache_name = self.field.get_cache_name()
  64. @cached_property
  65. def RelatedObjectDoesNotExist(self):
  66. # The exception can't be created at initialization time since the
  67. # related model might not be resolved yet; `rel.model` might still be
  68. # a string model reference.
  69. return type(
  70. 'RelatedObjectDoesNotExist',
  71. (self.field.remote_field.model.DoesNotExist, AttributeError),
  72. {}
  73. )
  74. def is_cached(self, instance):
  75. return hasattr(instance, self.cache_name)
  76. def get_queryset(self, **hints):
  77. return self.field.remote_field.model._base_manager.db_manager(hints=hints).all()
  78. def get_prefetch_queryset(self, instances, queryset=None):
  79. if queryset is None:
  80. queryset = self.get_queryset()
  81. queryset._add_hints(instance=instances[0])
  82. rel_obj_attr = self.field.get_foreign_related_value
  83. instance_attr = self.field.get_local_related_value
  84. instances_dict = {instance_attr(inst): inst for inst in instances}
  85. related_field = self.field.foreign_related_fields[0]
  86. # FIXME: This will need to be revisited when we introduce support for
  87. # composite fields. In the meantime we take this practical approach to
  88. # solve a regression on 1.6 when the reverse manager in hidden
  89. # (related_name ends with a '+'). Refs #21410.
  90. # The check for len(...) == 1 is a special case that allows the query
  91. # to be join-less and smaller. Refs #21760.
  92. if self.field.remote_field.is_hidden() or len(self.field.foreign_related_fields) == 1:
  93. query = {'%s__in' % related_field.name: {instance_attr(inst)[0] for inst in instances}}
  94. else:
  95. query = {'%s__in' % self.field.related_query_name(): instances}
  96. queryset = queryset.filter(**query)
  97. # Since we're going to assign directly in the cache,
  98. # we must manage the reverse relation cache manually.
  99. if not self.field.remote_field.multiple:
  100. rel_obj_cache_name = self.field.remote_field.get_cache_name()
  101. for rel_obj in queryset:
  102. instance = instances_dict[rel_obj_attr(rel_obj)]
  103. setattr(rel_obj, rel_obj_cache_name, instance)
  104. return queryset, rel_obj_attr, instance_attr, True, self.cache_name
  105. def get_object(self, instance):
  106. qs = self.get_queryset(instance=instance)
  107. # Assuming the database enforces foreign keys, this won't fail.
  108. return qs.get(self.field.get_reverse_related_filter(instance))
  109. def __get__(self, instance, cls=None):
  110. """
  111. Get the related instance through the forward relation.
  112. With the example above, when getting ``child.parent``:
  113. - ``self`` is the descriptor managing the ``parent`` attribute
  114. - ``instance`` is the ``child`` instance
  115. - ``cls`` is the ``Child`` class (we don't need it)
  116. """
  117. if instance is None:
  118. return self
  119. # The related instance is loaded from the database and then cached in
  120. # the attribute defined in self.cache_name. It can also be pre-cached
  121. # by the reverse accessor (ReverseOneToOneDescriptor).
  122. try:
  123. rel_obj = getattr(instance, self.cache_name)
  124. except AttributeError:
  125. val = self.field.get_local_related_value(instance)
  126. if None in val:
  127. rel_obj = None
  128. else:
  129. rel_obj = self.get_object(instance)
  130. # If this is a one-to-one relation, set the reverse accessor
  131. # cache on the related object to the current instance to avoid
  132. # an extra SQL query if it's accessed later on.
  133. if not self.field.remote_field.multiple:
  134. setattr(rel_obj, self.field.remote_field.get_cache_name(), instance)
  135. setattr(instance, self.cache_name, rel_obj)
  136. if rel_obj is None and not self.field.null:
  137. raise self.RelatedObjectDoesNotExist(
  138. "%s has no %s." % (self.field.model.__name__, self.field.name)
  139. )
  140. else:
  141. return rel_obj
  142. def __set__(self, instance, value):
  143. """
  144. Set the related instance through the forward relation.
  145. With the example above, when setting ``child.parent = parent``:
  146. - ``self`` is the descriptor managing the ``parent`` attribute
  147. - ``instance`` is the ``child`` instance
  148. - ``value`` is the ``parent`` instance on the right of the equal sign
  149. """
  150. # An object must be an instance of the related class.
  151. if value is not None and not isinstance(value, self.field.remote_field.model._meta.concrete_model):
  152. raise ValueError(
  153. 'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
  154. value,
  155. instance._meta.object_name,
  156. self.field.name,
  157. self.field.remote_field.model._meta.object_name,
  158. )
  159. )
  160. elif value is not None:
  161. if instance._state.db is None:
  162. instance._state.db = router.db_for_write(instance.__class__, instance=value)
  163. elif value._state.db is None:
  164. value._state.db = router.db_for_write(value.__class__, instance=instance)
  165. elif value._state.db is not None and instance._state.db is not None:
  166. if not router.allow_relation(value, instance):
  167. raise ValueError('Cannot assign "%r": the current database router prevents this relation.' % value)
  168. # If we're setting the value of a OneToOneField to None, we need to clear
  169. # out the cache on any old related object. Otherwise, deleting the
  170. # previously-related object will also cause this object to be deleted,
  171. # which is wrong.
  172. if value is None:
  173. # Look up the previously-related object, which may still be available
  174. # since we've not yet cleared out the related field.
  175. # Use the cache directly, instead of the accessor; if we haven't
  176. # populated the cache, then we don't care - we're only accessing
  177. # the object to invalidate the accessor cache, so there's no
  178. # need to populate the cache just to expire it again.
  179. related = getattr(instance, self.cache_name, None)
  180. # If we've got an old related object, we need to clear out its
  181. # cache. This cache also might not exist if the related object
  182. # hasn't been accessed yet.
  183. if related is not None:
  184. setattr(related, self.field.remote_field.get_cache_name(), None)
  185. for lh_field, rh_field in self.field.related_fields:
  186. setattr(instance, lh_field.attname, None)
  187. # Set the values of the related field.
  188. else:
  189. for lh_field, rh_field in self.field.related_fields:
  190. setattr(instance, lh_field.attname, getattr(value, rh_field.attname))
  191. # Set the related instance cache used by __get__ to avoid an SQL query
  192. # when accessing the attribute we just set.
  193. setattr(instance, self.cache_name, value)
  194. # If this is a one-to-one relation, set the reverse accessor cache on
  195. # the related object to the current instance to avoid an extra SQL
  196. # query if it's accessed later on.
  197. if value is not None and not self.field.remote_field.multiple:
  198. setattr(value, self.field.remote_field.get_cache_name(), instance)
  199. class ForwardOneToOneDescriptor(ForwardManyToOneDescriptor):
  200. """
  201. Accessor to the related object on the forward side of a one-to-one relation.
  202. In the example::
  203. class Restaurant(Model):
  204. place = OneToOneField(Place, related_name='restaurant')
  205. ``restaurant.place`` is a ``ForwardOneToOneDescriptor`` instance.
  206. """
  207. def get_object(self, instance):
  208. if self.field.remote_field.parent_link:
  209. deferred = instance.get_deferred_fields()
  210. # Because it's a parent link, all the data is available in the
  211. # instance, so populate the parent model with this data.
  212. rel_model = self.field.remote_field.model
  213. fields = [field.attname for field in rel_model._meta.concrete_fields]
  214. # If any of the related model's fields are deferred, fallback to
  215. # fetching all fields from the related model. This avoids a query
  216. # on the related model for every deferred field.
  217. if not any(field in fields for field in deferred):
  218. kwargs = {field: getattr(instance, field) for field in fields}
  219. obj = rel_model(**kwargs)
  220. obj._state.adding = instance._state.adding
  221. obj._state.db = instance._state.db
  222. return obj
  223. return super().get_object(instance)
  224. class ReverseOneToOneDescriptor:
  225. """
  226. Accessor to the related object on the reverse side of a one-to-one
  227. relation.
  228. In the example::
  229. class Restaurant(Model):
  230. place = OneToOneField(Place, related_name='restaurant')
  231. ``place.restaurant`` is a ``ReverseOneToOneDescriptor`` instance.
  232. """
  233. def __init__(self, related):
  234. self.related = related
  235. self.cache_name = related.get_cache_name()
  236. @cached_property
  237. def RelatedObjectDoesNotExist(self):
  238. # The exception isn't created at initialization time for the sake of
  239. # consistency with `ForwardManyToOneDescriptor`.
  240. return type(
  241. 'RelatedObjectDoesNotExist',
  242. (self.related.related_model.DoesNotExist, AttributeError),
  243. {}
  244. )
  245. def is_cached(self, instance):
  246. return hasattr(instance, self.cache_name)
  247. def get_queryset(self, **hints):
  248. return self.related.related_model._base_manager.db_manager(hints=hints).all()
  249. def get_prefetch_queryset(self, instances, queryset=None):
  250. if queryset is None:
  251. queryset = self.get_queryset()
  252. queryset._add_hints(instance=instances[0])
  253. rel_obj_attr = attrgetter(self.related.field.attname)
  254. def instance_attr(obj):
  255. return obj._get_pk_val()
  256. instances_dict = {instance_attr(inst): inst for inst in instances}
  257. query = {'%s__in' % self.related.field.name: instances}
  258. queryset = queryset.filter(**query)
  259. # Since we're going to assign directly in the cache,
  260. # we must manage the reverse relation cache manually.
  261. rel_obj_cache_name = self.related.field.get_cache_name()
  262. for rel_obj in queryset:
  263. instance = instances_dict[rel_obj_attr(rel_obj)]
  264. setattr(rel_obj, rel_obj_cache_name, instance)
  265. return queryset, rel_obj_attr, instance_attr, True, self.cache_name
  266. def __get__(self, instance, cls=None):
  267. """
  268. Get the related instance through the reverse relation.
  269. With the example above, when getting ``place.restaurant``:
  270. - ``self`` is the descriptor managing the ``restaurant`` attribute
  271. - ``instance`` is the ``place`` instance
  272. - ``cls`` is the ``Place`` class (unused)
  273. Keep in mind that ``Restaurant`` holds the foreign key to ``Place``.
  274. """
  275. if instance is None:
  276. return self
  277. # The related instance is loaded from the database and then cached in
  278. # the attribute defined in self.cache_name. It can also be pre-cached
  279. # by the forward accessor (ForwardManyToOneDescriptor).
  280. try:
  281. rel_obj = getattr(instance, self.cache_name)
  282. except AttributeError:
  283. related_pk = instance._get_pk_val()
  284. if related_pk is None:
  285. rel_obj = None
  286. else:
  287. filter_args = self.related.field.get_forward_related_filter(instance)
  288. try:
  289. rel_obj = self.get_queryset(instance=instance).get(**filter_args)
  290. except self.related.related_model.DoesNotExist:
  291. rel_obj = None
  292. else:
  293. # Set the forward accessor cache on the related object to
  294. # the current instance to avoid an extra SQL query if it's
  295. # accessed later on.
  296. setattr(rel_obj, self.related.field.get_cache_name(), instance)
  297. setattr(instance, self.cache_name, rel_obj)
  298. if rel_obj is None:
  299. raise self.RelatedObjectDoesNotExist(
  300. "%s has no %s." % (
  301. instance.__class__.__name__,
  302. self.related.get_accessor_name()
  303. )
  304. )
  305. else:
  306. return rel_obj
  307. def __set__(self, instance, value):
  308. """
  309. Set the related instance through the reverse relation.
  310. With the example above, when setting ``place.restaurant = restaurant``:
  311. - ``self`` is the descriptor managing the ``restaurant`` attribute
  312. - ``instance`` is the ``place`` instance
  313. - ``value`` is the ``restaurant`` instance on the right of the equal sign
  314. Keep in mind that ``Restaurant`` holds the foreign key to ``Place``.
  315. """
  316. # The similarity of the code below to the code in
  317. # ForwardManyToOneDescriptor is annoying, but there's a bunch
  318. # of small differences that would make a common base class convoluted.
  319. if value is None:
  320. # Update the cached related instance (if any) & clear the cache.
  321. try:
  322. rel_obj = getattr(instance, self.cache_name)
  323. except AttributeError:
  324. pass
  325. else:
  326. delattr(instance, self.cache_name)
  327. setattr(rel_obj, self.related.field.name, None)
  328. elif not isinstance(value, self.related.related_model):
  329. # An object must be an instance of the related class.
  330. raise ValueError(
  331. 'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
  332. value,
  333. instance._meta.object_name,
  334. self.related.get_accessor_name(),
  335. self.related.related_model._meta.object_name,
  336. )
  337. )
  338. else:
  339. if instance._state.db is None:
  340. instance._state.db = router.db_for_write(instance.__class__, instance=value)
  341. elif value._state.db is None:
  342. value._state.db = router.db_for_write(value.__class__, instance=instance)
  343. elif value._state.db is not None and instance._state.db is not None:
  344. if not router.allow_relation(value, instance):
  345. raise ValueError('Cannot assign "%r": the current database router prevents this relation.' % value)
  346. related_pk = tuple(getattr(instance, field.attname) for field in self.related.field.foreign_related_fields)
  347. # Set the value of the related field to the value of the related object's related field
  348. for index, field in enumerate(self.related.field.local_related_fields):
  349. setattr(value, field.attname, related_pk[index])
  350. # Set the related instance cache used by __get__ to avoid an SQL query
  351. # when accessing the attribute we just set.
  352. setattr(instance, self.cache_name, value)
  353. # Set the forward accessor cache on the related object to the current
  354. # instance to avoid an extra SQL query if it's accessed later on.
  355. setattr(value, self.related.field.get_cache_name(), instance)
  356. class ReverseManyToOneDescriptor:
  357. """
  358. Accessor to the related objects manager on the reverse side of a
  359. many-to-one relation.
  360. In the example::
  361. class Child(Model):
  362. parent = ForeignKey(Parent, related_name='children')
  363. ``parent.children`` is a ``ReverseManyToOneDescriptor`` instance.
  364. Most of the implementation is delegated to a dynamically defined manager
  365. class built by ``create_forward_many_to_many_manager()`` defined below.
  366. """
  367. def __init__(self, rel):
  368. self.rel = rel
  369. self.field = rel.field
  370. @cached_property
  371. def related_manager_cls(self):
  372. related_model = self.rel.related_model
  373. return create_reverse_many_to_one_manager(
  374. related_model._default_manager.__class__,
  375. self.rel,
  376. )
  377. def __get__(self, instance, cls=None):
  378. """
  379. Get the related objects through the reverse relation.
  380. With the example above, when getting ``parent.children``:
  381. - ``self`` is the descriptor managing the ``children`` attribute
  382. - ``instance`` is the ``parent`` instance
  383. - ``cls`` is the ``Parent`` class (unused)
  384. """
  385. if instance is None:
  386. return self
  387. return self.related_manager_cls(instance)
  388. def _get_set_deprecation_msg_params(self):
  389. return (
  390. 'reverse side of a related set',
  391. self.rel.get_accessor_name(),
  392. )
  393. def __set__(self, instance, value):
  394. raise TypeError(
  395. 'Direct assignment to the %s is prohibited. Use %s.set() instead.'
  396. % self._get_set_deprecation_msg_params(),
  397. )
  398. def create_reverse_many_to_one_manager(superclass, rel):
  399. """
  400. Create a manager for the reverse side of a many-to-one relation.
  401. This manager subclasses another manager, generally the default manager of
  402. the related model, and adds behaviors specific to many-to-one relations.
  403. """
  404. class RelatedManager(superclass):
  405. def __init__(self, instance):
  406. super().__init__()
  407. self.instance = instance
  408. self.model = rel.related_model
  409. self.field = rel.field
  410. self.core_filters = {self.field.name: instance}
  411. def __call__(self, *, manager):
  412. manager = getattr(self.model, manager)
  413. manager_class = create_reverse_many_to_one_manager(manager.__class__, rel)
  414. return manager_class(self.instance)
  415. do_not_call_in_templates = True
  416. def _apply_rel_filters(self, queryset):
  417. """
  418. Filter the queryset for the instance this manager is bound to.
  419. """
  420. db = self._db or router.db_for_read(self.model, instance=self.instance)
  421. empty_strings_as_null = connections[db].features.interprets_empty_strings_as_nulls
  422. queryset._add_hints(instance=self.instance)
  423. if self._db:
  424. queryset = queryset.using(self._db)
  425. queryset = queryset.filter(**self.core_filters)
  426. for field in self.field.foreign_related_fields:
  427. val = getattr(self.instance, field.attname)
  428. if val is None or (val == '' and empty_strings_as_null):
  429. return queryset.none()
  430. queryset._known_related_objects = {self.field: {self.instance.pk: self.instance}}
  431. return queryset
  432. def _remove_prefetched_objects(self):
  433. try:
  434. self.instance._prefetched_objects_cache.pop(self.field.related_query_name())
  435. except (AttributeError, KeyError):
  436. pass # nothing to clear from cache
  437. def get_queryset(self):
  438. try:
  439. return self.instance._prefetched_objects_cache[self.field.related_query_name()]
  440. except (AttributeError, KeyError):
  441. queryset = super().get_queryset()
  442. return self._apply_rel_filters(queryset)
  443. def get_prefetch_queryset(self, instances, queryset=None):
  444. if queryset is None:
  445. queryset = super().get_queryset()
  446. queryset._add_hints(instance=instances[0])
  447. queryset = queryset.using(queryset._db or self._db)
  448. rel_obj_attr = self.field.get_local_related_value
  449. instance_attr = self.field.get_foreign_related_value
  450. instances_dict = {instance_attr(inst): inst for inst in instances}
  451. query = {'%s__in' % self.field.name: instances}
  452. queryset = queryset.filter(**query)
  453. # Since we just bypassed this class' get_queryset(), we must manage
  454. # the reverse relation manually.
  455. for rel_obj in queryset:
  456. instance = instances_dict[rel_obj_attr(rel_obj)]
  457. setattr(rel_obj, self.field.name, instance)
  458. cache_name = self.field.related_query_name()
  459. return queryset, rel_obj_attr, instance_attr, False, cache_name
  460. def add(self, *objs, bulk=True):
  461. self._remove_prefetched_objects()
  462. objs = list(objs)
  463. db = router.db_for_write(self.model, instance=self.instance)
  464. def check_and_update_obj(obj):
  465. if not isinstance(obj, self.model):
  466. raise TypeError("'%s' instance expected, got %r" % (
  467. self.model._meta.object_name, obj,
  468. ))
  469. setattr(obj, self.field.name, self.instance)
  470. if bulk:
  471. pks = []
  472. for obj in objs:
  473. check_and_update_obj(obj)
  474. if obj._state.adding or obj._state.db != db:
  475. raise ValueError(
  476. "%r instance isn't saved. Use bulk=False or save "
  477. "the object first." % obj
  478. )
  479. pks.append(obj.pk)
  480. self.model._base_manager.using(db).filter(pk__in=pks).update(**{
  481. self.field.name: self.instance,
  482. })
  483. else:
  484. with transaction.atomic(using=db, savepoint=False):
  485. for obj in objs:
  486. check_and_update_obj(obj)
  487. obj.save()
  488. add.alters_data = True
  489. def create(self, **kwargs):
  490. kwargs[self.field.name] = self.instance
  491. db = router.db_for_write(self.model, instance=self.instance)
  492. return super(RelatedManager, self.db_manager(db)).create(**kwargs)
  493. create.alters_data = True
  494. def get_or_create(self, **kwargs):
  495. kwargs[self.field.name] = self.instance
  496. db = router.db_for_write(self.model, instance=self.instance)
  497. return super(RelatedManager, self.db_manager(db)).get_or_create(**kwargs)
  498. get_or_create.alters_data = True
  499. def update_or_create(self, **kwargs):
  500. kwargs[self.field.name] = self.instance
  501. db = router.db_for_write(self.model, instance=self.instance)
  502. return super(RelatedManager, self.db_manager(db)).update_or_create(**kwargs)
  503. update_or_create.alters_data = True
  504. # remove() and clear() are only provided if the ForeignKey can have a value of null.
  505. if rel.field.null:
  506. def remove(self, *objs, bulk=True):
  507. if not objs:
  508. return
  509. val = self.field.get_foreign_related_value(self.instance)
  510. old_ids = set()
  511. for obj in objs:
  512. # Is obj actually part of this descriptor set?
  513. if self.field.get_local_related_value(obj) == val:
  514. old_ids.add(obj.pk)
  515. else:
  516. raise self.field.remote_field.model.DoesNotExist(
  517. "%r is not related to %r." % (obj, self.instance)
  518. )
  519. self._clear(self.filter(pk__in=old_ids), bulk)
  520. remove.alters_data = True
  521. def clear(self, *, bulk=True):
  522. self._clear(self, bulk)
  523. clear.alters_data = True
  524. def _clear(self, queryset, bulk):
  525. self._remove_prefetched_objects()
  526. db = router.db_for_write(self.model, instance=self.instance)
  527. queryset = queryset.using(db)
  528. if bulk:
  529. # `QuerySet.update()` is intrinsically atomic.
  530. queryset.update(**{self.field.name: None})
  531. else:
  532. with transaction.atomic(using=db, savepoint=False):
  533. for obj in queryset:
  534. setattr(obj, self.field.name, None)
  535. obj.save(update_fields=[self.field.name])
  536. _clear.alters_data = True
  537. def set(self, objs, *, bulk=True, clear=False):
  538. # Force evaluation of `objs` in case it's a queryset whose value
  539. # could be affected by `manager.clear()`. Refs #19816.
  540. objs = tuple(objs)
  541. if self.field.null:
  542. db = router.db_for_write(self.model, instance=self.instance)
  543. with transaction.atomic(using=db, savepoint=False):
  544. if clear:
  545. self.clear()
  546. self.add(*objs, bulk=bulk)
  547. else:
  548. old_objs = set(self.using(db).all())
  549. new_objs = []
  550. for obj in objs:
  551. if obj in old_objs:
  552. old_objs.remove(obj)
  553. else:
  554. new_objs.append(obj)
  555. self.remove(*old_objs, bulk=bulk)
  556. self.add(*new_objs, bulk=bulk)
  557. else:
  558. self.add(*objs, bulk=bulk)
  559. set.alters_data = True
  560. return RelatedManager
  561. class ManyToManyDescriptor(ReverseManyToOneDescriptor):
  562. """
  563. Accessor to the related objects manager on the forward and reverse sides of
  564. a many-to-many relation.
  565. In the example::
  566. class Pizza(Model):
  567. toppings = ManyToManyField(Topping, related_name='pizzas')
  568. ``pizza.toppings`` and ``topping.pizzas`` are ``ManyToManyDescriptor``
  569. instances.
  570. Most of the implementation is delegated to a dynamically defined manager
  571. class built by ``create_forward_many_to_many_manager()`` defined below.
  572. """
  573. def __init__(self, rel, reverse=False):
  574. super().__init__(rel)
  575. self.reverse = reverse
  576. @property
  577. def through(self):
  578. # through is provided so that you have easy access to the through
  579. # model (Book.authors.through) for inlines, etc. This is done as
  580. # a property to ensure that the fully resolved value is returned.
  581. return self.rel.through
  582. @cached_property
  583. def related_manager_cls(self):
  584. related_model = self.rel.related_model if self.reverse else self.rel.model
  585. return create_forward_many_to_many_manager(
  586. related_model._default_manager.__class__,
  587. self.rel,
  588. reverse=self.reverse,
  589. )
  590. def _get_set_deprecation_msg_params(self):
  591. return (
  592. '%s side of a many-to-many set' % ('reverse' if self.reverse else 'forward'),
  593. self.rel.get_accessor_name() if self.reverse else self.field.name,
  594. )
  595. def create_forward_many_to_many_manager(superclass, rel, reverse):
  596. """
  597. Create a manager for the either side of a many-to-many relation.
  598. This manager subclasses another manager, generally the default manager of
  599. the related model, and adds behaviors specific to many-to-many relations.
  600. """
  601. class ManyRelatedManager(superclass):
  602. def __init__(self, instance=None):
  603. super().__init__()
  604. self.instance = instance
  605. if not reverse:
  606. self.model = rel.model
  607. self.query_field_name = rel.field.related_query_name()
  608. self.prefetch_cache_name = rel.field.name
  609. self.source_field_name = rel.field.m2m_field_name()
  610. self.target_field_name = rel.field.m2m_reverse_field_name()
  611. self.symmetrical = rel.symmetrical
  612. else:
  613. self.model = rel.related_model
  614. self.query_field_name = rel.field.name
  615. self.prefetch_cache_name = rel.field.related_query_name()
  616. self.source_field_name = rel.field.m2m_reverse_field_name()
  617. self.target_field_name = rel.field.m2m_field_name()
  618. self.symmetrical = False
  619. self.through = rel.through
  620. self.reverse = reverse
  621. self.source_field = self.through._meta.get_field(self.source_field_name)
  622. self.target_field = self.through._meta.get_field(self.target_field_name)
  623. self.core_filters = {}
  624. self.pk_field_names = {}
  625. for lh_field, rh_field in self.source_field.related_fields:
  626. core_filter_key = '%s__%s' % (self.query_field_name, rh_field.name)
  627. self.core_filters[core_filter_key] = getattr(instance, rh_field.attname)
  628. self.pk_field_names[lh_field.name] = rh_field.name
  629. self.related_val = self.source_field.get_foreign_related_value(instance)
  630. if None in self.related_val:
  631. raise ValueError('"%r" needs to have a value for field "%s" before '
  632. 'this many-to-many relationship can be used.' %
  633. (instance, self.pk_field_names[self.source_field_name]))
  634. # Even if this relation is not to pk, we require still pk value.
  635. # The wish is that the instance has been already saved to DB,
  636. # although having a pk value isn't a guarantee of that.
  637. if instance.pk is None:
  638. raise ValueError("%r instance needs to have a primary key value before "
  639. "a many-to-many relationship can be used." %
  640. instance.__class__.__name__)
  641. def __call__(self, *, manager):
  642. manager = getattr(self.model, manager)
  643. manager_class = create_forward_many_to_many_manager(manager.__class__, rel, reverse)
  644. return manager_class(instance=self.instance)
  645. do_not_call_in_templates = True
  646. def _build_remove_filters(self, removed_vals):
  647. filters = Q(**{self.source_field_name: self.related_val})
  648. # No need to add a subquery condition if removed_vals is a QuerySet without
  649. # filters.
  650. removed_vals_filters = (not isinstance(removed_vals, QuerySet) or
  651. removed_vals._has_filters())
  652. if removed_vals_filters:
  653. filters &= Q(**{'%s__in' % self.target_field_name: removed_vals})
  654. if self.symmetrical:
  655. symmetrical_filters = Q(**{self.target_field_name: self.related_val})
  656. if removed_vals_filters:
  657. symmetrical_filters &= Q(
  658. **{'%s__in' % self.source_field_name: removed_vals})
  659. filters |= symmetrical_filters
  660. return filters
  661. def _apply_rel_filters(self, queryset):
  662. """
  663. Filter the queryset for the instance this manager is bound to.
  664. """
  665. queryset._add_hints(instance=self.instance)
  666. if self._db:
  667. queryset = queryset.using(self._db)
  668. return queryset._next_is_sticky().filter(**self.core_filters)
  669. def _remove_prefetched_objects(self):
  670. try:
  671. self.instance._prefetched_objects_cache.pop(self.prefetch_cache_name)
  672. except (AttributeError, KeyError):
  673. pass # nothing to clear from cache
  674. def get_queryset(self):
  675. try:
  676. return self.instance._prefetched_objects_cache[self.prefetch_cache_name]
  677. except (AttributeError, KeyError):
  678. queryset = super().get_queryset()
  679. return self._apply_rel_filters(queryset)
  680. def get_prefetch_queryset(self, instances, queryset=None):
  681. if queryset is None:
  682. queryset = super().get_queryset()
  683. queryset._add_hints(instance=instances[0])
  684. queryset = queryset.using(queryset._db or self._db)
  685. query = {'%s__in' % self.query_field_name: instances}
  686. queryset = queryset._next_is_sticky().filter(**query)
  687. # M2M: need to annotate the query in order to get the primary model
  688. # that the secondary model was actually related to. We know that
  689. # there will already be a join on the join table, so we can just add
  690. # the select.
  691. # For non-autocreated 'through' models, can't assume we are
  692. # dealing with PK values.
  693. fk = self.through._meta.get_field(self.source_field_name)
  694. join_table = fk.model._meta.db_table
  695. connection = connections[queryset.db]
  696. qn = connection.ops.quote_name
  697. queryset = queryset.extra(select={
  698. '_prefetch_related_val_%s' % f.attname:
  699. '%s.%s' % (qn(join_table), qn(f.column)) for f in fk.local_related_fields})
  700. return (
  701. queryset,
  702. lambda result: tuple(
  703. getattr(result, '_prefetch_related_val_%s' % f.attname)
  704. for f in fk.local_related_fields
  705. ),
  706. lambda inst: tuple(
  707. f.get_db_prep_value(getattr(inst, f.attname), connection)
  708. for f in fk.foreign_related_fields
  709. ),
  710. False,
  711. self.prefetch_cache_name,
  712. )
  713. def add(self, *objs):
  714. if not rel.through._meta.auto_created:
  715. opts = self.through._meta
  716. raise AttributeError(
  717. "Cannot use add() on a ManyToManyField which specifies an "
  718. "intermediary model. Use %s.%s's Manager instead." %
  719. (opts.app_label, opts.object_name)
  720. )
  721. self._remove_prefetched_objects()
  722. db = router.db_for_write(self.through, instance=self.instance)
  723. with transaction.atomic(using=db, savepoint=False):
  724. self._add_items(self.source_field_name, self.target_field_name, *objs)
  725. # If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table
  726. if self.symmetrical:
  727. self._add_items(self.target_field_name, self.source_field_name, *objs)
  728. add.alters_data = True
  729. def remove(self, *objs):
  730. if not rel.through._meta.auto_created:
  731. opts = self.through._meta
  732. raise AttributeError(
  733. "Cannot use remove() on a ManyToManyField which specifies "
  734. "an intermediary model. Use %s.%s's Manager instead." %
  735. (opts.app_label, opts.object_name)
  736. )
  737. self._remove_prefetched_objects()
  738. self._remove_items(self.source_field_name, self.target_field_name, *objs)
  739. remove.alters_data = True
  740. def clear(self):
  741. db = router.db_for_write(self.through, instance=self.instance)
  742. with transaction.atomic(using=db, savepoint=False):
  743. signals.m2m_changed.send(
  744. sender=self.through, action="pre_clear",
  745. instance=self.instance, reverse=self.reverse,
  746. model=self.model, pk_set=None, using=db,
  747. )
  748. self._remove_prefetched_objects()
  749. filters = self._build_remove_filters(super().get_queryset().using(db))
  750. self.through._default_manager.using(db).filter(filters).delete()
  751. signals.m2m_changed.send(
  752. sender=self.through, action="post_clear",
  753. instance=self.instance, reverse=self.reverse,
  754. model=self.model, pk_set=None, using=db,
  755. )
  756. clear.alters_data = True
  757. def set(self, objs, *, clear=False):
  758. if not rel.through._meta.auto_created:
  759. opts = self.through._meta
  760. raise AttributeError(
  761. "Cannot set values on a ManyToManyField which specifies an "
  762. "intermediary model. Use %s.%s's Manager instead." %
  763. (opts.app_label, opts.object_name)
  764. )
  765. # Force evaluation of `objs` in case it's a queryset whose value
  766. # could be affected by `manager.clear()`. Refs #19816.
  767. objs = tuple(objs)
  768. db = router.db_for_write(self.through, instance=self.instance)
  769. with transaction.atomic(using=db, savepoint=False):
  770. if clear:
  771. self.clear()
  772. self.add(*objs)
  773. else:
  774. old_ids = set(self.using(db).values_list(self.target_field.target_field.attname, flat=True))
  775. new_objs = []
  776. for obj in objs:
  777. fk_val = (
  778. self.target_field.get_foreign_related_value(obj)[0]
  779. if isinstance(obj, self.model) else obj
  780. )
  781. if fk_val in old_ids:
  782. old_ids.remove(fk_val)
  783. else:
  784. new_objs.append(obj)
  785. self.remove(*old_ids)
  786. self.add(*new_objs)
  787. set.alters_data = True
  788. def create(self, **kwargs):
  789. # This check needs to be done here, since we can't later remove this
  790. # from the method lookup table, as we do with add and remove.
  791. if not self.through._meta.auto_created:
  792. opts = self.through._meta
  793. raise AttributeError(
  794. "Cannot use create() on a ManyToManyField which specifies "
  795. "an intermediary model. Use %s.%s's Manager instead." %
  796. (opts.app_label, opts.object_name)
  797. )
  798. db = router.db_for_write(self.instance.__class__, instance=self.instance)
  799. new_obj = super(ManyRelatedManager, self.db_manager(db)).create(**kwargs)
  800. self.add(new_obj)
  801. return new_obj
  802. create.alters_data = True
  803. def get_or_create(self, **kwargs):
  804. db = router.db_for_write(self.instance.__class__, instance=self.instance)
  805. obj, created = super(ManyRelatedManager, self.db_manager(db)).get_or_create(**kwargs)
  806. # We only need to add() if created because if we got an object back
  807. # from get() then the relationship already exists.
  808. if created:
  809. self.add(obj)
  810. return obj, created
  811. get_or_create.alters_data = True
  812. def update_or_create(self, **kwargs):
  813. db = router.db_for_write(self.instance.__class__, instance=self.instance)
  814. obj, created = super(ManyRelatedManager, self.db_manager(db)).update_or_create(**kwargs)
  815. # We only need to add() if created because if we got an object back
  816. # from get() then the relationship already exists.
  817. if created:
  818. self.add(obj)
  819. return obj, created
  820. update_or_create.alters_data = True
  821. def _add_items(self, source_field_name, target_field_name, *objs):
  822. # source_field_name: the PK fieldname in join table for the source object
  823. # target_field_name: the PK fieldname in join table for the target object
  824. # *objs - objects to add. Either object instances, or primary keys of object instances.
  825. # If there aren't any objects, there is nothing to do.
  826. from django.db.models import Model
  827. if objs:
  828. new_ids = set()
  829. for obj in objs:
  830. if isinstance(obj, self.model):
  831. if not router.allow_relation(obj, self.instance):
  832. raise ValueError(
  833. 'Cannot add "%r": instance is on database "%s", value is on database "%s"' %
  834. (obj, self.instance._state.db, obj._state.db)
  835. )
  836. fk_val = self.through._meta.get_field(
  837. target_field_name).get_foreign_related_value(obj)[0]
  838. if fk_val is None:
  839. raise ValueError(
  840. 'Cannot add "%r": the value for field "%s" is None' %
  841. (obj, target_field_name)
  842. )
  843. new_ids.add(fk_val)
  844. elif isinstance(obj, Model):
  845. raise TypeError(
  846. "'%s' instance expected, got %r" %
  847. (self.model._meta.object_name, obj)
  848. )
  849. else:
  850. new_ids.add(obj)
  851. db = router.db_for_write(self.through, instance=self.instance)
  852. vals = (self.through._default_manager.using(db)
  853. .values_list(target_field_name, flat=True)
  854. .filter(**{
  855. source_field_name: self.related_val[0],
  856. '%s__in' % target_field_name: new_ids,
  857. }))
  858. new_ids = new_ids - set(vals)
  859. with transaction.atomic(using=db, savepoint=False):
  860. if self.reverse or source_field_name == self.source_field_name:
  861. # Don't send the signal when we are inserting the
  862. # duplicate data row for symmetrical reverse entries.
  863. signals.m2m_changed.send(
  864. sender=self.through, action='pre_add',
  865. instance=self.instance, reverse=self.reverse,
  866. model=self.model, pk_set=new_ids, using=db,
  867. )
  868. # Add the ones that aren't there already
  869. self.through._default_manager.using(db).bulk_create([
  870. self.through(**{
  871. '%s_id' % source_field_name: self.related_val[0],
  872. '%s_id' % target_field_name: obj_id,
  873. })
  874. for obj_id in new_ids
  875. ])
  876. if self.reverse or source_field_name == self.source_field_name:
  877. # Don't send the signal when we are inserting the
  878. # duplicate data row for symmetrical reverse entries.
  879. signals.m2m_changed.send(
  880. sender=self.through, action='post_add',
  881. instance=self.instance, reverse=self.reverse,
  882. model=self.model, pk_set=new_ids, using=db,
  883. )
  884. def _remove_items(self, source_field_name, target_field_name, *objs):
  885. # source_field_name: the PK colname in join table for the source object
  886. # target_field_name: the PK colname in join table for the target object
  887. # *objs - objects to remove
  888. if not objs:
  889. return
  890. # Check that all the objects are of the right type
  891. old_ids = set()
  892. for obj in objs:
  893. if isinstance(obj, self.model):
  894. fk_val = self.target_field.get_foreign_related_value(obj)[0]
  895. old_ids.add(fk_val)
  896. else:
  897. old_ids.add(obj)
  898. db = router.db_for_write(self.through, instance=self.instance)
  899. with transaction.atomic(using=db, savepoint=False):
  900. # Send a signal to the other end if need be.
  901. signals.m2m_changed.send(
  902. sender=self.through, action="pre_remove",
  903. instance=self.instance, reverse=self.reverse,
  904. model=self.model, pk_set=old_ids, using=db,
  905. )
  906. target_model_qs = super().get_queryset()
  907. if target_model_qs._has_filters():
  908. old_vals = target_model_qs.using(db).filter(**{
  909. '%s__in' % self.target_field.target_field.attname: old_ids})
  910. else:
  911. old_vals = old_ids
  912. filters = self._build_remove_filters(old_vals)
  913. self.through._default_manager.using(db).filter(filters).delete()
  914. signals.m2m_changed.send(
  915. sender=self.through, action="post_remove",
  916. instance=self.instance, reverse=self.reverse,
  917. model=self.model, pk_set=old_ids, using=db,
  918. )
  919. return ManyRelatedManager