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

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