related_descriptors.py 46 KB

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