Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

related_descriptors.py 50KB

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