| 1 |
import functools |
| 2 |
import inspect |
| 3 |
import warnings |
| 4 |
from functools import partial |
| 5 |
|
| 6 |
from django import forms |
| 7 |
from django.apps import apps |
| 8 |
from django.conf import SettingsReference, settings |
| 9 |
from django.core import checks, exceptions |
| 10 |
from django.db import connection, router |
| 11 |
from django.db.backends import utils |
| 12 |
from django.db.models import Q |
| 13 |
from django.db.models.constants import LOOKUP_SEP |
| 14 |
from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL |
| 15 |
from django.db.models.query_utils import PathInfo |
| 16 |
from django.db.models.utils import make_model_tuple |
| 17 |
from django.utils.deprecation import RemovedInDjango60Warning |
| 18 |
from django.utils.functional import cached_property |
| 19 |
from django.utils.translation import gettext_lazy as _ |
| 20 |
|
| 21 |
from . import Field |
| 22 |
from .mixins import FieldCacheMixin |
| 23 |
from .related_descriptors import ( |
| 24 |
ForeignKeyDeferredAttribute, |
| 25 |
ForwardManyToOneDescriptor, |
| 26 |
ForwardOneToOneDescriptor, |
| 27 |
ManyToManyDescriptor, |
| 28 |
ReverseManyToOneDescriptor, |
| 29 |
ReverseOneToOneDescriptor, |
| 30 |
) |
| 31 |
from .related_lookups import ( |
| 32 |
RelatedExact, |
| 33 |
RelatedGreaterThan, |
| 34 |
RelatedGreaterThanOrEqual, |
| 35 |
RelatedIn, |
| 36 |
RelatedIsNull, |
| 37 |
RelatedLessThan, |
| 38 |
RelatedLessThanOrEqual, |
| 39 |
) |
| 40 |
from .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel |
| 41 |
|
| 42 |
RECURSIVE_RELATIONSHIP_CONSTANT = "self" |
| 43 |
|
| 44 |
|
| 45 |
def resolve_relation(scope_model, relation): |
| 46 |
""" |
| 47 |
Transform relation into a model or fully-qualified model string of the form |
| 48 |
"app_label.ModelName", relative to scope_model. |
| 49 |
|
| 50 |
The relation argument can be: |
| 51 |
* RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case |
| 52 |
the model argument will be returned. |
| 53 |
* A bare model name without an app_label, in which case scope_model's |
| 54 |
app_label will be prepended. |
| 55 |
* An "app_label.ModelName" string. |
| 56 |
* A model class, which will be returned unchanged. |
| 57 |
""" |
| 58 |
# Check for recursive relations |
| 59 |
if relation == RECURSIVE_RELATIONSHIP_CONSTANT: |
| 60 |
relation = scope_model |
| 61 |
|
| 62 |
# Look for an "app.Model" relation |
| 63 |
if isinstance(relation, str): |
| 64 |
if "." not in relation: |
| 65 |
relation = "%s.%s" % (scope_model._meta.app_label, relation) |
| 66 |
|
| 67 |
return relation |
| 68 |
|
| 69 |
|
| 70 |
def lazy_related_operation(function, model, *related_models, **kwargs): |
| 71 |
""" |
| 72 |
Schedule `function` to be called once `model` and all `related_models` |
| 73 |
have been imported and registered with the app registry. `function` will |
| 74 |
be called with the newly-loaded model classes as its positional arguments, |
| 75 |
plus any optional keyword arguments. |
| 76 |
|
| 77 |
The `model` argument must be a model class. Each subsequent positional |
| 78 |
argument is another model, or a reference to another model - see |
| 79 |
`resolve_relation()` for the various forms these may take. Any relative |
| 80 |
references will be resolved relative to `model`. |
| 81 |
|
| 82 |
This is a convenience wrapper for `Apps.lazy_model_operation` - the app |
| 83 |
registry model used is the one found in `model._meta.apps`. |
| 84 |
""" |
| 85 |
models = [model] + [resolve_relation(model, rel) for rel in related_models] |
| 86 |
model_keys = (make_model_tuple(m) for m in models) |
| 87 |
apps = model._meta.apps |
| 88 |
return apps.lazy_model_operation(partial(function, **kwargs), *model_keys) |
| 89 |
|
| 90 |
|
| 91 |
class RelatedField(FieldCacheMixin, Field): |
| 92 |
"""Base class that all relational fields inherit from.""" |
| 93 |
|
| 94 |
# Field flags |
| 95 |
one_to_many = False |
| 96 |
one_to_one = False |
| 97 |
many_to_many = False |
| 98 |
many_to_one = False |
| 99 |
|
| 100 |
def __init__( |
| 101 |
self, |
| 102 |
related_name=None, |
| 103 |
related_query_name=None, |
| 104 |
limit_choices_to=None, |
| 105 |
**kwargs, |
| 106 |
): |
| 107 |
self._related_name = related_name |
| 108 |
self._related_query_name = related_query_name |
| 109 |
self._limit_choices_to = limit_choices_to |
| 110 |
super().__init__(**kwargs) |
| 111 |
|
| 112 |
@cached_property |
| 113 |
def related_model(self): |
| 114 |
# Can't cache this property until all the models are loaded. |
| 115 |
apps.check_models_ready() |
| 116 |
return self.remote_field.model |
| 117 |
|
| 118 |
def check(self, **kwargs): |
| 119 |
return [ |
| 120 |
*super().check(**kwargs), |
| 121 |
*self._check_related_name_is_valid(), |
| 122 |
*self._check_related_query_name_is_valid(), |
| 123 |
*self._check_relation_model_exists(), |
| 124 |
*self._check_referencing_to_swapped_model(), |
| 125 |
*self._check_clashes(), |
| 126 |
] |
| 127 |
|
| 128 |
def _check_related_name_is_valid(self): |
| 129 |
import keyword |
| 130 |
|
| 131 |
related_name = self.remote_field.related_name |
| 132 |
if related_name is None: |
| 133 |
return [] |
| 134 |
is_valid_id = ( |
| 135 |
not keyword.iskeyword(related_name) and related_name.isidentifier() |
| 136 |
) |
| 137 |
if not (is_valid_id or related_name.endswith("+")): |
| 138 |
return [ |
| 139 |
checks.Error( |
| 140 |
"The name '%s' is invalid related_name for field %s.%s" |
| 141 |
% ( |
| 142 |
self.remote_field.related_name, |
| 143 |
self.model._meta.object_name, |
| 144 |
self.name, |
| 145 |
), |
| 146 |
hint=( |
| 147 |
"Related name must be a valid Python identifier or end with a " |
| 148 |
"'+'" |
| 149 |
), |
| 150 |
obj=self, |
| 151 |
id="fields.E306", |
| 152 |
) |
| 153 |
] |
| 154 |
return [] |
| 155 |
|
| 156 |
def _check_related_query_name_is_valid(self): |
| 157 |
if self.remote_field.hidden: |
| 158 |
return [] |
| 159 |
rel_query_name = self.related_query_name() |
| 160 |
errors = [] |
| 161 |
if rel_query_name.endswith("_"): |
| 162 |
errors.append( |
| 163 |
checks.Error( |
| 164 |
"Reverse query name '%s' must not end with an underscore." |
| 165 |
% rel_query_name, |
| 166 |
hint=( |
| 167 |
"Add or change a related_name or related_query_name " |
| 168 |
"argument for this field." |
| 169 |
), |
| 170 |
obj=self, |
| 171 |
id="fields.E308", |
| 172 |
) |
| 173 |
) |
| 174 |
if LOOKUP_SEP in rel_query_name: |
| 175 |
errors.append( |
| 176 |
checks.Error( |
| 177 |
"Reverse query name '%s' must not contain '%s'." |
| 178 |
% (rel_query_name, LOOKUP_SEP), |
| 179 |
hint=( |
| 180 |
"Add or change a related_name or related_query_name " |
| 181 |
"argument for this field." |
| 182 |
), |
| 183 |
obj=self, |
| 184 |
id="fields.E309", |
| 185 |
) |
| 186 |
) |
| 187 |
return errors |
| 188 |
|
| 189 |
def _check_relation_model_exists(self): |
| 190 |
rel_is_missing = self.remote_field.model not in self.opts.apps.get_models( |
| 191 |
include_auto_created=True |
| 192 |
) |
| 193 |
rel_is_string = isinstance(self.remote_field.model, str) |
| 194 |
model_name = ( |
| 195 |
self.remote_field.model |
| 196 |
if rel_is_string |
| 197 |
else self.remote_field.model._meta.object_name |
| 198 |
) |
| 199 |
if rel_is_missing and ( |
| 200 |
rel_is_string or not self.remote_field.model._meta.swapped |
| 201 |
): |
| 202 |
return [ |
| 203 |
checks.Error( |
| 204 |
"Field defines a relation with model '%s', which is either " |
| 205 |
"not installed, or is abstract." % model_name, |
| 206 |
obj=self, |
| 207 |
id="fields.E300", |
| 208 |
) |
| 209 |
] |
| 210 |
return [] |
| 211 |
|
| 212 |
def _check_referencing_to_swapped_model(self): |
| 213 |
if ( |
| 214 |
self.remote_field.model not in self.opts.apps.get_models() |
| 215 |
and not isinstance(self.remote_field.model, str) |
| 216 |
and self.remote_field.model._meta.swapped |
| 217 |
): |
| 218 |
return [ |
| 219 |
checks.Error( |
| 220 |
"Field defines a relation with the model '%s', which has " |
| 221 |
"been swapped out." % self.remote_field.model._meta.label, |
| 222 |
hint="Update the relation to point at 'settings.%s'." |
| 223 |
% self.remote_field.model._meta.swappable, |
| 224 |
obj=self, |
| 225 |
id="fields.E301", |
| 226 |
) |
| 227 |
] |
| 228 |
return [] |
| 229 |
|
| 230 |
def _check_clashes(self): |
| 231 |
"""Check accessor and reverse query name clashes.""" |
| 232 |
from django.db.models.base import ModelBase |
| 233 |
|
| 234 |
errors = [] |
| 235 |
opts = self.model._meta |
| 236 |
|
| 237 |
# f.remote_field.model may be a string instead of a model. Skip if |
| 238 |
# model name is not resolved. |
| 239 |
if not isinstance(self.remote_field.model, ModelBase): |
| 240 |
return [] |
| 241 |
|
| 242 |
# Consider that we are checking field `Model.foreign` and the models |
| 243 |
# are: |
| 244 |
# |
| 245 |
# class Target(models.Model): |
| 246 |
# model = models.IntegerField() |
| 247 |
# model_set = models.IntegerField() |
| 248 |
# |
| 249 |
# class Model(models.Model): |
| 250 |
# foreign = models.ForeignKey(Target) |
| 251 |
# m2m = models.ManyToManyField(Target) |
| 252 |
|
| 253 |
# rel_opts.object_name == "Target" |
| 254 |
rel_opts = self.remote_field.model._meta |
| 255 |
# If the field doesn't install a backward relation on the target model |
| 256 |
# (so `is_hidden` returns True), then there are no clashes to check |
| 257 |
# and we can skip these fields. |
| 258 |
rel_is_hidden = self.remote_field.hidden |
| 259 |
rel_name = self.remote_field.accessor_name # i. e. "model_set" |
| 260 |
rel_query_name = self.related_query_name() # i. e. "model" |
| 261 |
# i.e. "app_label.Model.field". |
| 262 |
field_name = "%s.%s" % (opts.label, self.name) |
| 263 |
|
| 264 |
# Check clashes between accessor or reverse query name of `field` |
| 265 |
# and any other field name -- i.e. accessor for Model.foreign is |
| 266 |
# model_set and it clashes with Target.model_set. |
| 267 |
potential_clashes = rel_opts.fields + rel_opts.many_to_many |
| 268 |
for clash_field in potential_clashes: |
| 269 |
if not rel_is_hidden and clash_field.name == rel_name: |
| 270 |
clash_name = f"{rel_opts.label}.{clash_field.name}" |
| 271 |
errors.append( |
| 272 |
checks.Error( |
| 273 |
f"Reverse accessor '{rel_opts.object_name}.{rel_name}' " |
| 274 |
f"for '{field_name}' clashes with field name " |
| 275 |
f"'{clash_name}'.", |
| 276 |
hint=( |
| 277 |
"Rename field '%s', or add/change a related_name " |
| 278 |
"argument to the definition for field '%s'." |
| 279 |
) |
| 280 |
% (clash_name, field_name), |
| 281 |
obj=self, |
| 282 |
id="fields.E302", |
| 283 |
) |
| 284 |
) |
| 285 |
|
| 286 |
if clash_field.name == rel_query_name: |
| 287 |
clash_name = f"{rel_opts.label}.{clash_field.name}" |
| 288 |
errors.append( |
| 289 |
checks.Error( |
| 290 |
"Reverse query name for '%s' clashes with field name '%s'." |
| 291 |
% (field_name, clash_name), |
| 292 |
hint=( |
| 293 |
"Rename field '%s', or add/change a related_name " |
| 294 |
"argument to the definition for field '%s'." |
| 295 |
) |
| 296 |
% (clash_name, field_name), |
| 297 |
obj=self, |
| 298 |
id="fields.E303", |
| 299 |
) |
| 300 |
) |
| 301 |
|
| 302 |
# Check clashes between accessors/reverse query names of `field` and |
| 303 |
# any other field accessor -- i. e. Model.foreign accessor clashes with |
| 304 |
# Model.m2m accessor. |
| 305 |
potential_clashes = (r for r in rel_opts.related_objects if r.field is not self) |
| 306 |
for clash_field in potential_clashes: |
| 307 |
if not rel_is_hidden and clash_field.accessor_name == rel_name: |
| 308 |
clash_name = ( |
| 309 |
f"{clash_field.related_model._meta.label}.{clash_field.field.name}" |
| 310 |
) |
| 311 |
errors.append( |
| 312 |
checks.Error( |
| 313 |
f"Reverse accessor '{rel_opts.object_name}.{rel_name}' " |
| 314 |
f"for '{field_name}' clashes with reverse accessor for " |
| 315 |
f"'{clash_name}'.", |
| 316 |
hint=( |
| 317 |
"Add or change a related_name argument " |
| 318 |
"to the definition for '%s' or '%s'." |
| 319 |
) |
| 320 |
% (field_name, clash_name), |
| 321 |
obj=self, |
| 322 |
id="fields.E304", |
| 323 |
) |
| 324 |
) |
| 325 |
|
| 326 |
if clash_field.accessor_name == rel_query_name: |
| 327 |
clash_name = ( |
| 328 |
f"{clash_field.related_model._meta.label}.{clash_field.field.name}" |
| 329 |
) |
| 330 |
errors.append( |
| 331 |
checks.Error( |
| 332 |
"Reverse query name for '%s' clashes with reverse query name " |
| 333 |
"for '%s'." % (field_name, clash_name), |
| 334 |
hint=( |
| 335 |
"Add or change a related_name argument " |
| 336 |
"to the definition for '%s' or '%s'." |
| 337 |
) |
| 338 |
% (field_name, clash_name), |
| 339 |
obj=self, |
| 340 |
id="fields.E305", |
| 341 |
) |
| 342 |
) |
| 343 |
|
| 344 |
return errors |
| 345 |
|
| 346 |
def db_type(self, connection): |
| 347 |
# By default related field will not have a column as it relates to |
| 348 |
# columns from another table. |
| 349 |
return None |
| 350 |
|
| 351 |
def contribute_to_class(self, cls, name, private_only=False, **kwargs): |
| 352 |
super().contribute_to_class(cls, name, private_only=private_only, **kwargs) |
| 353 |
|
| 354 |
self.opts = cls._meta |
| 355 |
|
| 356 |
if not cls._meta.abstract: |
| 357 |
if self.remote_field.related_name: |
| 358 |
related_name = self.remote_field.related_name |
| 359 |
else: |
| 360 |
related_name = self.opts.default_related_name |
| 361 |
if related_name: |
| 362 |
related_name %= { |
| 363 |
"class": cls.__name__.lower(), |
| 364 |
"model_name": cls._meta.model_name.lower(), |
| 365 |
"app_label": cls._meta.app_label.lower(), |
| 366 |
} |
| 367 |
self.remote_field.related_name = related_name |
| 368 |
|
| 369 |
if self.remote_field.related_query_name: |
| 370 |
related_query_name = self.remote_field.related_query_name % { |
| 371 |
"class": cls.__name__.lower(), |
| 372 |
"app_label": cls._meta.app_label.lower(), |
| 373 |
} |
| 374 |
self.remote_field.related_query_name = related_query_name |
| 375 |
|
| 376 |
def resolve_related_class(model, related, field): |
| 377 |
field.remote_field.model = related |
| 378 |
field.do_related_class(related, model) |
| 379 |
|
| 380 |
lazy_related_operation( |
| 381 |
resolve_related_class, cls, self.remote_field.model, field=self |
| 382 |
) |
| 383 |
|
| 384 |
def deconstruct(self): |
| 385 |
name, path, args, kwargs = super().deconstruct() |
| 386 |
if self._limit_choices_to: |
| 387 |
kwargs["limit_choices_to"] = self._limit_choices_to |
| 388 |
if self._related_name is not None: |
| 389 |
kwargs["related_name"] = self._related_name |
| 390 |
if self._related_query_name is not None: |
| 391 |
kwargs["related_query_name"] = self._related_query_name |
| 392 |
return name, path, args, kwargs |
| 393 |
|
| 394 |
def get_forward_related_filter(self, obj): |
| 395 |
""" |
| 396 |
Return the keyword arguments that when supplied to |
| 397 |
self.model.object.filter(), would select all instances related through |
| 398 |
this field to the remote obj. This is used to build the querysets |
| 399 |
returned by related descriptors. obj is an instance of |
| 400 |
self.related_field.model. |
| 401 |
""" |
| 402 |
return { |
| 403 |
"%s__%s" % (self.name, rh_field.name): getattr(obj, rh_field.attname) |
| 404 |
for _, rh_field in self.related_fields |
| 405 |
} |
| 406 |
|
| 407 |
def get_reverse_related_filter(self, obj): |
| 408 |
""" |
| 409 |
Complement to get_forward_related_filter(). Return the keyword |
| 410 |
arguments that when passed to self.related_field.model.object.filter() |
| 411 |
select all instances of self.related_field.model related through |
| 412 |
this field to obj. obj is an instance of self.model. |
| 413 |
""" |
| 414 |
base_q = Q.create( |
| 415 |
[ |
| 416 |
(rh_field.attname, getattr(obj, lh_field.attname)) |
| 417 |
for lh_field, rh_field in self.related_fields |
| 418 |
] |
| 419 |
) |
| 420 |
descriptor_filter = self.get_extra_descriptor_filter(obj) |
| 421 |
if isinstance(descriptor_filter, dict): |
| 422 |
return base_q & Q(**descriptor_filter) |
| 423 |
elif descriptor_filter: |
| 424 |
return base_q & descriptor_filter |
| 425 |
return base_q |
| 426 |
|
| 427 |
@property |
| 428 |
def swappable_setting(self): |
| 429 |
""" |
| 430 |
Get the setting that this is powered from for swapping, or None |
| 431 |
if it's not swapped in / marked with swappable=False. |
| 432 |
""" |
| 433 |
if self.swappable: |
| 434 |
# Work out string form of "to" |
| 435 |
if isinstance(self.remote_field.model, str): |
| 436 |
to_string = self.remote_field.model |
| 437 |
else: |
| 438 |
to_string = self.remote_field.model._meta.label |
| 439 |
return apps.get_swappable_settings_name(to_string) |
| 440 |
return None |
| 441 |
|
| 442 |
def set_attributes_from_rel(self): |
| 443 |
self.name = self.name or ( |
| 444 |
self.remote_field.model._meta.model_name |
| 445 |
+ "_" |
| 446 |
+ self.remote_field.model._meta.pk.name |
| 447 |
) |
| 448 |
if self.verbose_name is None: |
| 449 |
self.verbose_name = self.remote_field.model._meta.verbose_name |
| 450 |
self.remote_field.set_field_name() |
| 451 |
|
| 452 |
def do_related_class(self, other, cls): |
| 453 |
self.set_attributes_from_rel() |
| 454 |
self.contribute_to_related_class(other, self.remote_field) |
| 455 |
|
| 456 |
def get_limit_choices_to(self): |
| 457 |
""" |
| 458 |
Return ``limit_choices_to`` for this model field. |
| 459 |
|
| 460 |
If it is a callable, it will be invoked and the result will be |
| 461 |
returned. |
| 462 |
""" |
| 463 |
if callable(self.remote_field.limit_choices_to): |
| 464 |
return self.remote_field.limit_choices_to() |
| 465 |
return self.remote_field.limit_choices_to |
| 466 |
|
| 467 |
def formfield(self, **kwargs): |
| 468 |
""" |
| 469 |
Pass ``limit_choices_to`` to the field being constructed. |
| 470 |
|
| 471 |
Only passes it if there is a type that supports related fields. |
| 472 |
This is a similar strategy used to pass the ``queryset`` to the field |
| 473 |
being constructed. |
| 474 |
""" |
| 475 |
defaults = {} |
| 476 |
if hasattr(self.remote_field, "get_related_field"): |
| 477 |
# If this is a callable, do not invoke it here. Just pass |
| 478 |
# it in the defaults for when the form class will later be |
| 479 |
# instantiated. |
| 480 |
limit_choices_to = self.remote_field.limit_choices_to |
| 481 |
defaults.update( |
| 482 |
{ |
| 483 |
"limit_choices_to": limit_choices_to, |
| 484 |
} |
| 485 |
) |
| 486 |
defaults.update(kwargs) |
| 487 |
return super().formfield(**defaults) |
| 488 |
|
| 489 |
def related_query_name(self): |
| 490 |
""" |
| 491 |
Define the name that can be used to identify this related object in a |
| 492 |
table-spanning query. |
| 493 |
""" |
| 494 |
return ( |
| 495 |
self.remote_field.related_query_name |
| 496 |
or self.remote_field.related_name |
| 497 |
or self.opts.model_name |
| 498 |
) |
| 499 |
|
| 500 |
@property |
| 501 |
def target_field(self): |
| 502 |
""" |
| 503 |
When filtering against this relation, return the field on the remote |
| 504 |
model against which the filtering should happen. |
| 505 |
""" |
| 506 |
target_fields = self.path_infos[-1].target_fields |
| 507 |
if len(target_fields) > 1: |
| 508 |
raise exceptions.FieldError( |
| 509 |
"The relation has multiple target fields, but only single target field " |
| 510 |
"was asked for" |
| 511 |
) |
| 512 |
return target_fields[0] |
| 513 |
|
| 514 |
@cached_property |
| 515 |
def cache_name(self): |
| 516 |
return self.name |
| 517 |
|
| 518 |
|
| 519 |
class ForeignObject(RelatedField): |
| 520 |
""" |
| 521 |
Abstraction of the ForeignKey relation to support multi-column relations. |
| 522 |
""" |
| 523 |
|
| 524 |
# Field flags |
| 525 |
many_to_many = False |
| 526 |
many_to_one = True |
| 527 |
one_to_many = False |
| 528 |
one_to_one = False |
| 529 |
|
| 530 |
requires_unique_target = True |
| 531 |
related_accessor_class = ReverseManyToOneDescriptor |
| 532 |
forward_related_accessor_class = ForwardManyToOneDescriptor |
| 533 |
rel_class = ForeignObjectRel |
| 534 |
|
| 535 |
def __init__( |
| 536 |
self, |
| 537 |
to, |
| 538 |
on_delete, |
| 539 |
from_fields, |
| 540 |
to_fields, |
| 541 |
rel=None, |
| 542 |
related_name=None, |
| 543 |
related_query_name=None, |
| 544 |
limit_choices_to=None, |
| 545 |
parent_link=False, |
| 546 |
swappable=True, |
| 547 |
**kwargs, |
| 548 |
): |
| 549 |
if rel is None: |
| 550 |
rel = self.rel_class( |
| 551 |
self, |
| 552 |
to, |
| 553 |
related_name=related_name, |
| 554 |
related_query_name=related_query_name, |
| 555 |
limit_choices_to=limit_choices_to, |
| 556 |
parent_link=parent_link, |
| 557 |
on_delete=on_delete, |
| 558 |
) |
| 559 |
|
| 560 |
super().__init__( |
| 561 |
rel=rel, |
| 562 |
related_name=related_name, |
| 563 |
related_query_name=related_query_name, |
| 564 |
limit_choices_to=limit_choices_to, |
| 565 |
**kwargs, |
| 566 |
) |
| 567 |
|
| 568 |
self.from_fields = from_fields |
| 569 |
self.to_fields = to_fields |
| 570 |
self.swappable = swappable |
| 571 |
|
| 572 |
def __copy__(self): |
| 573 |
obj = super().__copy__() |
| 574 |
# Remove any cached PathInfo values. |
| 575 |
obj.__dict__.pop("path_infos", None) |
| 576 |
obj.__dict__.pop("reverse_path_infos", None) |
| 577 |
return obj |
| 578 |
|
| 579 |
def check(self, **kwargs): |
| 580 |
return [ |
| 581 |
*super().check(**kwargs), |
| 582 |
*self._check_to_fields_exist(), |
| 583 |
*self._check_to_fields_composite_pk(), |
| 584 |
*self._check_unique_target(), |
| 585 |
] |
| 586 |
|
| 587 |
def _check_to_fields_exist(self): |
| 588 |
# Skip nonexistent models. |
| 589 |
if isinstance(self.remote_field.model, str): |
| 590 |
return [] |
| 591 |
|
| 592 |
errors = [] |
| 593 |
for to_field in self.to_fields: |
| 594 |
if to_field: |
| 595 |
try: |
| 596 |
self.remote_field.model._meta.get_field(to_field) |
| 597 |
except exceptions.FieldDoesNotExist: |
| 598 |
errors.append( |
| 599 |
checks.Error( |
| 600 |
"The to_field '%s' doesn't exist on the related " |
| 601 |
"model '%s'." |
| 602 |
% (to_field, self.remote_field.model._meta.label), |
| 603 |
obj=self, |
| 604 |
id="fields.E312", |
| 605 |
) |
| 606 |
) |
| 607 |
return errors |
| 608 |
|
| 609 |
def _check_to_fields_composite_pk(self): |
| 610 |
from django.db.models.fields.composite import CompositePrimaryKey |
| 611 |
|
| 612 |
# Skip nonexistent models. |
| 613 |
if isinstance(self.remote_field.model, str): |
| 614 |
return [] |
| 615 |
|
| 616 |
errors = [] |
| 617 |
for to_field in self.to_fields: |
| 618 |
try: |
| 619 |
field = ( |
| 620 |
self.remote_field.model._meta.pk |
| 621 |
if to_field is None |
| 622 |
else self.remote_field.model._meta.get_field(to_field) |
| 623 |
) |
| 624 |
except exceptions.FieldDoesNotExist: |
| 625 |
pass |
| 626 |
else: |
| 627 |
if isinstance(field, CompositePrimaryKey): |
| 628 |
errors.append( |
| 629 |
checks.Error( |
| 630 |
"Field defines a relation involving model " |
| 631 |
f"{self.remote_field.model._meta.object_name!r} which has " |
| 632 |
"a CompositePrimaryKey and such relations are not " |
| 633 |
"supported.", |
| 634 |
obj=self, |
| 635 |
id="fields.E347", |
| 636 |
) |
| 637 |
) |
| 638 |
return errors |
| 639 |
|
| 640 |
def _check_unique_target(self): |
| 641 |
rel_is_string = isinstance(self.remote_field.model, str) |
| 642 |
if rel_is_string or not self.requires_unique_target: |
| 643 |
return [] |
| 644 |
|
| 645 |
try: |
| 646 |
self.foreign_related_fields |
| 647 |
except exceptions.FieldDoesNotExist: |
| 648 |
return [] |
| 649 |
|
| 650 |
if not self.foreign_related_fields: |
| 651 |
return [] |
| 652 |
|
| 653 |
has_unique_constraint = any( |
| 654 |
rel_field.unique for rel_field in self.foreign_related_fields |
| 655 |
) |
| 656 |
if not has_unique_constraint: |
| 657 |
foreign_fields = {f.name for f in self.foreign_related_fields} |
| 658 |
remote_opts = self.remote_field.model._meta |
| 659 |
has_unique_constraint = ( |
| 660 |
any( |
| 661 |
frozenset(ut) <= foreign_fields |
| 662 |
for ut in remote_opts.unique_together |
| 663 |
) |
| 664 |
or any( |
| 665 |
frozenset(uc.fields) <= foreign_fields |
| 666 |
for uc in remote_opts.total_unique_constraints |
| 667 |
) |
| 668 |
# If the model defines a composite primary key and the foreign key |
| 669 |
# refers to it, the target is unique. |
| 670 |
or ( |
| 671 |
frozenset(field.name for field in remote_opts.pk_fields) |
| 672 |
== foreign_fields |
| 673 |
) |
| 674 |
) |
| 675 |
|
| 676 |
if not has_unique_constraint: |
| 677 |
if len(self.foreign_related_fields) > 1: |
| 678 |
field_combination = ", ".join( |
| 679 |
f"'{rel_field.name}'" for rel_field in self.foreign_related_fields |
| 680 |
) |
| 681 |
model_name = self.remote_field.model.__name__ |
| 682 |
return [ |
| 683 |
checks.Error( |
| 684 |
f"No subset of the fields {field_combination} on model " |
| 685 |
f"'{model_name}' is unique.", |
| 686 |
hint=( |
| 687 |
"Mark a single field as unique=True or add a set of " |
| 688 |
"fields to a unique constraint (via unique_together " |
| 689 |
"or a UniqueConstraint (without condition) in the " |
| 690 |
"model Meta.constraints)." |
| 691 |
), |
| 692 |
obj=self, |
| 693 |
id="fields.E310", |
| 694 |
) |
| 695 |
] |
| 696 |
else: |
| 697 |
field_name = self.foreign_related_fields[0].name |
| 698 |
model_name = self.remote_field.model.__name__ |
| 699 |
return [ |
| 700 |
checks.Error( |
| 701 |
f"'{model_name}.{field_name}' must be unique because it is " |
| 702 |
"referenced by a foreign key.", |
| 703 |
hint=( |
| 704 |
"Add unique=True to this field or add a " |
| 705 |
"UniqueConstraint (without condition) in the model " |
| 706 |
"Meta.constraints." |
| 707 |
), |
| 708 |
obj=self, |
| 709 |
id="fields.E311", |
| 710 |
) |
| 711 |
] |
| 712 |
return [] |
| 713 |
|
| 714 |
def deconstruct(self): |
| 715 |
name, path, args, kwargs = super().deconstruct() |
| 716 |
kwargs["on_delete"] = self.remote_field.on_delete |
| 717 |
kwargs["from_fields"] = self.from_fields |
| 718 |
kwargs["to_fields"] = self.to_fields |
| 719 |
|
| 720 |
if self.remote_field.parent_link: |
| 721 |
kwargs["parent_link"] = self.remote_field.parent_link |
| 722 |
if isinstance(self.remote_field.model, str): |
| 723 |
if "." in self.remote_field.model: |
| 724 |
app_label, model_name = self.remote_field.model.split(".") |
| 725 |
kwargs["to"] = "%s.%s" % (app_label, model_name.lower()) |
| 726 |
else: |
| 727 |
kwargs["to"] = self.remote_field.model.lower() |
| 728 |
else: |
| 729 |
kwargs["to"] = self.remote_field.model._meta.label_lower |
| 730 |
# If swappable is True, then see if we're actually pointing to the target |
| 731 |
# of a swap. |
| 732 |
swappable_setting = self.swappable_setting |
| 733 |
if swappable_setting is not None: |
| 734 |
# If it's already a settings reference, error |
| 735 |
if hasattr(kwargs["to"], "setting_name"): |
| 736 |
if kwargs["to"].setting_name != swappable_setting: |
| 737 |
raise ValueError( |
| 738 |
"Cannot deconstruct a ForeignKey pointing to a model " |
| 739 |
"that is swapped in place of more than one model (%s and %s)" |
| 740 |
% (kwargs["to"].setting_name, swappable_setting) |
| 741 |
) |
| 742 |
# Set it |
| 743 |
kwargs["to"] = SettingsReference( |
| 744 |
kwargs["to"], |
| 745 |
swappable_setting, |
| 746 |
) |
| 747 |
return name, path, args, kwargs |
| 748 |
|
| 749 |
def resolve_related_fields(self): |
| 750 |
if not self.from_fields or len(self.from_fields) != len(self.to_fields): |
| 751 |
raise ValueError( |
| 752 |
"Foreign Object from and to fields must be the same non-zero length" |
| 753 |
) |
| 754 |
if isinstance(self.remote_field.model, str): |
| 755 |
raise ValueError( |
| 756 |
"Related model %r cannot be resolved" % self.remote_field.model |
| 757 |
) |
| 758 |
related_fields = [] |
| 759 |
for from_field_name, to_field_name in zip(self.from_fields, self.to_fields): |
| 760 |
from_field = ( |
| 761 |
self |
| 762 |
if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT |
| 763 |
else self.opts.get_field(from_field_name) |
| 764 |
) |
| 765 |
to_field = ( |
| 766 |
self.remote_field.model._meta.pk |
| 767 |
if to_field_name is None |
| 768 |
else self.remote_field.model._meta.get_field(to_field_name) |
| 769 |
) |
| 770 |
related_fields.append((from_field, to_field)) |
| 771 |
return related_fields |
| 772 |
|
| 773 |
@cached_property |
| 774 |
def related_fields(self): |
| 775 |
return self.resolve_related_fields() |
| 776 |
|
| 777 |
@cached_property |
| 778 |
def reverse_related_fields(self): |
| 779 |
return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields] |
| 780 |
|
| 781 |
@cached_property |
| 782 |
def local_related_fields(self): |
| 783 |
return tuple(lhs_field for lhs_field, rhs_field in self.related_fields) |
| 784 |
|
| 785 |
@cached_property |
| 786 |
def foreign_related_fields(self): |
| 787 |
return tuple( |
| 788 |
rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field |
| 789 |
) |
| 790 |
|
| 791 |
def get_local_related_value(self, instance): |
| 792 |
return self.get_instance_value_for_fields(instance, self.local_related_fields) |
| 793 |
|
| 794 |
def get_foreign_related_value(self, instance): |
| 795 |
return self.get_instance_value_for_fields(instance, self.foreign_related_fields) |
| 796 |
|
| 797 |
@staticmethod |
| 798 |
def get_instance_value_for_fields(instance, fields): |
| 799 |
ret = [] |
| 800 |
opts = instance._meta |
| 801 |
for field in fields: |
| 802 |
# Gotcha: in some cases (like fixture loading) a model can have |
| 803 |
# different values in parent_ptr_id and parent's id. So, use |
| 804 |
# instance.pk (that is, parent_ptr_id) when asked for instance.id. |
| 805 |
if field.primary_key: |
| 806 |
possible_parent_link = opts.get_ancestor_link(field.model) |
| 807 |
if ( |
| 808 |
not possible_parent_link |
| 809 |
or possible_parent_link.primary_key |
| 810 |
or possible_parent_link.model._meta.abstract |
| 811 |
): |
| 812 |
ret.append(instance.pk) |
| 813 |
continue |
| 814 |
ret.append(getattr(instance, field.attname)) |
| 815 |
return tuple(ret) |
| 816 |
|
| 817 |
def get_attname_column(self): |
| 818 |
attname, column = super().get_attname_column() |
| 819 |
return attname, None |
| 820 |
|
| 821 |
def get_joining_columns(self, reverse_join=False): |
| 822 |
warnings.warn( |
| 823 |
"ForeignObject.get_joining_columns() is deprecated. Use " |
| 824 |
"get_joining_fields() instead.", |
| 825 |
RemovedInDjango60Warning, |
| 826 |
stacklevel=2, |
| 827 |
) |
| 828 |
source = self.reverse_related_fields if reverse_join else self.related_fields |
| 829 |
return tuple( |
| 830 |
(lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source |
| 831 |
) |
| 832 |
|
| 833 |
def get_reverse_joining_columns(self): |
| 834 |
warnings.warn( |
| 835 |
"ForeignObject.get_reverse_joining_columns() is deprecated. Use " |
| 836 |
"get_reverse_joining_fields() instead.", |
| 837 |
RemovedInDjango60Warning, |
| 838 |
stacklevel=2, |
| 839 |
) |
| 840 |
return self.get_joining_columns(reverse_join=True) |
| 841 |
|
| 842 |
def get_joining_fields(self, reverse_join=False): |
| 843 |
return tuple( |
| 844 |
self.reverse_related_fields if reverse_join else self.related_fields |
| 845 |
) |
| 846 |
|
| 847 |
def get_reverse_joining_fields(self): |
| 848 |
return self.get_joining_fields(reverse_join=True) |
| 849 |
|
| 850 |
def get_extra_descriptor_filter(self, instance): |
| 851 |
""" |
| 852 |
Return an extra filter condition for related object fetching when |
| 853 |
user does 'instance.fieldname', that is the extra filter is used in |
| 854 |
the descriptor of the field. |
| 855 |
|
| 856 |
The filter should be either a dict usable in .filter(**kwargs) call or |
| 857 |
a Q-object. The condition will be ANDed together with the relation's |
| 858 |
joining columns. |
| 859 |
|
| 860 |
A parallel method is get_extra_restriction() which is used in |
| 861 |
JOIN and subquery conditions. |
| 862 |
""" |
| 863 |
return {} |
| 864 |
|
| 865 |
def get_extra_restriction(self, alias, related_alias): |
| 866 |
""" |
| 867 |
Return a pair condition used for joining and subquery pushdown. The |
| 868 |
condition is something that responds to as_sql(compiler, connection) |
| 869 |
method. |
| 870 |
|
| 871 |
Note that currently referring both the 'alias' and 'related_alias' |
| 872 |
will not work in some conditions, like subquery pushdown. |
| 873 |
|
| 874 |
A parallel method is get_extra_descriptor_filter() which is used in |
| 875 |
instance.fieldname related object fetching. |
| 876 |
""" |
| 877 |
return None |
| 878 |
|
| 879 |
def get_path_info(self, filtered_relation=None): |
| 880 |
"""Get path from this field to the related model.""" |
| 881 |
opts = self.remote_field.model._meta |
| 882 |
from_opts = self.model._meta |
| 883 |
return [ |
| 884 |
PathInfo( |
| 885 |
from_opts=from_opts, |
| 886 |
to_opts=opts, |
| 887 |
target_fields=self.foreign_related_fields, |
| 888 |
join_field=self, |
| 889 |
m2m=False, |
| 890 |
direct=True, |
| 891 |
filtered_relation=filtered_relation, |
| 892 |
) |
| 893 |
] |
| 894 |
|
| 895 |
@cached_property |
| 896 |
def path_infos(self): |
| 897 |
return self.get_path_info() |
| 898 |
|
| 899 |
def get_reverse_path_info(self, filtered_relation=None): |
| 900 |
"""Get path from the related model to this field's model.""" |
| 901 |
opts = self.model._meta |
| 902 |
from_opts = self.remote_field.model._meta |
| 903 |
return [ |
| 904 |
PathInfo( |
| 905 |
from_opts=from_opts, |
| 906 |
to_opts=opts, |
| 907 |
target_fields=(opts.pk,), |
| 908 |
join_field=self.remote_field, |
| 909 |
m2m=not self.unique, |
| 910 |
direct=False, |
| 911 |
filtered_relation=filtered_relation, |
| 912 |
) |
| 913 |
] |
| 914 |
|
| 915 |
@cached_property |
| 916 |
def reverse_path_infos(self): |
| 917 |
return self.get_reverse_path_info() |
| 918 |
|
| 919 |
@classmethod |
| 920 |
@functools.cache |
| 921 |
def get_class_lookups(cls): |
| 922 |
bases = inspect.getmro(cls) |
| 923 |
bases = bases[: bases.index(ForeignObject) + 1] |
| 924 |
class_lookups = [parent.__dict__.get("class_lookups", {}) for parent in bases] |
| 925 |
return cls.merge_dicts(class_lookups) |
| 926 |
|
| 927 |
def contribute_to_class(self, cls, name, private_only=False, **kwargs): |
| 928 |
super().contribute_to_class(cls, name, private_only=private_only, **kwargs) |
| 929 |
setattr(cls, self.name, self.forward_related_accessor_class(self)) |
| 930 |
|
| 931 |
def contribute_to_related_class(self, cls, related): |
| 932 |
# Internal FK's - i.e., those with a related name ending with '+' - |
| 933 |
# and swapped models don't get a related descriptor. |
| 934 |
if not self.remote_field.hidden and not related.related_model._meta.swapped: |
| 935 |
setattr( |
| 936 |
cls._meta.concrete_model, |
| 937 |
related.accessor_name, |
| 938 |
self.related_accessor_class(related), |
| 939 |
) |
| 940 |
# While 'limit_choices_to' might be a callable, simply pass |
| 941 |
# it along for later - this is too early because it's still |
| 942 |
# model load time. |
| 943 |
if self.remote_field.limit_choices_to: |
| 944 |
cls._meta.related_fkey_lookups.append( |
| 945 |
self.remote_field.limit_choices_to |
| 946 |
) |
| 947 |
|
| 948 |
|
| 949 |
ForeignObject.register_lookup(RelatedIn) |
| 950 |
ForeignObject.register_lookup(RelatedExact) |
| 951 |
ForeignObject.register_lookup(RelatedLessThan) |
| 952 |
ForeignObject.register_lookup(RelatedGreaterThan) |
| 953 |
ForeignObject.register_lookup(RelatedGreaterThanOrEqual) |
| 954 |
ForeignObject.register_lookup(RelatedLessThanOrEqual) |
| 955 |
ForeignObject.register_lookup(RelatedIsNull) |
| 956 |
|
| 957 |
|
| 958 |
class ForeignKey(ForeignObject): |
| 959 |
""" |
| 960 |
Provide a many-to-one relation by adding a column to the local model |
| 961 |
to hold the remote value. |
| 962 |
|
| 963 |
By default ForeignKey will target the pk of the remote model but this |
| 964 |
behavior can be changed by using the ``to_field`` argument. |
| 965 |
""" |
| 966 |
|
| 967 |
descriptor_class = ForeignKeyDeferredAttribute |
| 968 |
# Field flags |
| 969 |
many_to_many = False |
| 970 |
many_to_one = True |
| 971 |
one_to_many = False |
| 972 |
one_to_one = False |
| 973 |
|
| 974 |
rel_class = ManyToOneRel |
| 975 |
|
| 976 |
empty_strings_allowed = False |
| 977 |
default_error_messages = { |
| 978 |
"invalid": _( |
| 979 |
"%(model)s instance with %(field)s %(value)r is not a valid choice." |
| 980 |
) |
| 981 |
} |
| 982 |
description = _("Foreign Key (type determined by related field)") |
| 983 |
|
| 984 |
def __init__( |
| 985 |
self, |
| 986 |
to, |
| 987 |
on_delete, |
| 988 |
related_name=None, |
| 989 |
related_query_name=None, |
| 990 |
limit_choices_to=None, |
| 991 |
parent_link=False, |
| 992 |
to_field=None, |
| 993 |
db_constraint=True, |
| 994 |
**kwargs, |
| 995 |
): |
| 996 |
try: |
| 997 |
to._meta.model_name |
| 998 |
except AttributeError: |
| 999 |
if not isinstance(to, str): |
| 1000 |
raise TypeError( |
| 1001 |
"%s(%r) is invalid. First parameter to ForeignKey must be " |
| 1002 |
"either a model, a model name, or the string %r" |
| 1003 |
% ( |
| 1004 |
self.__class__.__name__, |
| 1005 |
to, |
| 1006 |
RECURSIVE_RELATIONSHIP_CONSTANT, |
| 1007 |
) |
| 1008 |
) |
| 1009 |
else: |
| 1010 |
# For backwards compatibility purposes, we need to *try* and set |
| 1011 |
# the to_field during FK construction. It won't be guaranteed to |
| 1012 |
# be correct until contribute_to_class is called. Refs #12190. |
| 1013 |
to_field = to_field or (to._meta.pk and to._meta.pk.name) |
| 1014 |
if not callable(on_delete): |
| 1015 |
raise TypeError("on_delete must be callable.") |
| 1016 |
|
| 1017 |
kwargs["rel"] = self.rel_class( |
| 1018 |
self, |
| 1019 |
to, |
| 1020 |
to_field, |
| 1021 |
related_name=related_name, |
| 1022 |
related_query_name=related_query_name, |
| 1023 |
limit_choices_to=limit_choices_to, |
| 1024 |
parent_link=parent_link, |
| 1025 |
on_delete=on_delete, |
| 1026 |
) |
| 1027 |
kwargs.setdefault("db_index", True) |
| 1028 |
|
| 1029 |
super().__init__( |
| 1030 |
to, |
| 1031 |
on_delete, |
| 1032 |
related_name=related_name, |
| 1033 |
related_query_name=related_query_name, |
| 1034 |
limit_choices_to=limit_choices_to, |
| 1035 |
from_fields=[RECURSIVE_RELATIONSHIP_CONSTANT], |
| 1036 |
to_fields=[to_field], |
| 1037 |
**kwargs, |
| 1038 |
) |
| 1039 |
self.db_constraint = db_constraint |
| 1040 |
|
| 1041 |
def __class_getitem__(cls, *args, **kwargs): |
| 1042 |
return cls |
| 1043 |
|
| 1044 |
def check(self, **kwargs): |
| 1045 |
return [ |
| 1046 |
*super().check(**kwargs), |
| 1047 |
*self._check_on_delete(), |
| 1048 |
*self._check_unique(), |
| 1049 |
] |
| 1050 |
|
| 1051 |
def _check_on_delete(self): |
| 1052 |
on_delete = getattr(self.remote_field, "on_delete", None) |
| 1053 |
if on_delete == SET_NULL and not self.null: |
| 1054 |
return [ |
| 1055 |
checks.Error( |
| 1056 |
"Field specifies on_delete=SET_NULL, but cannot be null.", |
| 1057 |
hint=( |
| 1058 |
"Set null=True argument on the field, or change the on_delete " |
| 1059 |
"rule." |
| 1060 |
), |
| 1061 |
obj=self, |
| 1062 |
id="fields.E320", |
| 1063 |
) |
| 1064 |
] |
| 1065 |
elif on_delete == SET_DEFAULT and not self.has_default(): |
| 1066 |
return [ |
| 1067 |
checks.Error( |
| 1068 |
"Field specifies on_delete=SET_DEFAULT, but has no default value.", |
| 1069 |
hint="Set a default value, or change the on_delete rule.", |
| 1070 |
obj=self, |
| 1071 |
id="fields.E321", |
| 1072 |
) |
| 1073 |
] |
| 1074 |
else: |
| 1075 |
return [] |
| 1076 |
|
| 1077 |
def _check_unique(self, **kwargs): |
| 1078 |
return ( |
| 1079 |
[ |
| 1080 |
checks.Warning( |
| 1081 |
"Setting unique=True on a ForeignKey has the same effect as using " |
| 1082 |
"a OneToOneField.", |
| 1083 |
hint=( |
| 1084 |
"ForeignKey(unique=True) is usually better served by a " |
| 1085 |
"OneToOneField." |
| 1086 |
), |
| 1087 |
obj=self, |
| 1088 |
id="fields.W342", |
| 1089 |
) |
| 1090 |
] |
| 1091 |
if self.unique |
| 1092 |
else [] |
| 1093 |
) |
| 1094 |
|
| 1095 |
def deconstruct(self): |
| 1096 |
name, path, args, kwargs = super().deconstruct() |
| 1097 |
del kwargs["to_fields"] |
| 1098 |
del kwargs["from_fields"] |
| 1099 |
# Handle the simpler arguments |
| 1100 |
if self.db_index: |
| 1101 |
del kwargs["db_index"] |
| 1102 |
else: |
| 1103 |
kwargs["db_index"] = False |
| 1104 |
if self.db_constraint is not True: |
| 1105 |
kwargs["db_constraint"] = self.db_constraint |
| 1106 |
# Rel needs more work. |
| 1107 |
to_meta = getattr(self.remote_field.model, "_meta", None) |
| 1108 |
if self.remote_field.field_name and ( |
| 1109 |
not to_meta |
| 1110 |
or (to_meta.pk and self.remote_field.field_name != to_meta.pk.name) |
| 1111 |
): |
| 1112 |
kwargs["to_field"] = self.remote_field.field_name |
| 1113 |
return name, path, args, kwargs |
| 1114 |
|
| 1115 |
def to_python(self, value): |
| 1116 |
return self.target_field.to_python(value) |
| 1117 |
|
| 1118 |
@property |
| 1119 |
def target_field(self): |
| 1120 |
return self.foreign_related_fields[0] |
| 1121 |
|
| 1122 |
def validate(self, value, model_instance): |
| 1123 |
if self.remote_field.parent_link: |
| 1124 |
return |
| 1125 |
super().validate(value, model_instance) |
| 1126 |
if value is None: |
| 1127 |
return |
| 1128 |
|
| 1129 |
using = router.db_for_read(self.remote_field.model, instance=model_instance) |
| 1130 |
qs = self.remote_field.model._base_manager.using(using).filter( |
| 1131 |
**{self.remote_field.field_name: value} |
| 1132 |
) |
| 1133 |
qs = qs.complex_filter(self.get_limit_choices_to()) |
| 1134 |
if not qs.exists(): |
| 1135 |
raise exceptions.ValidationError( |
| 1136 |
self.error_messages["invalid"], |
| 1137 |
code="invalid", |
| 1138 |
params={ |
| 1139 |
"model": self.remote_field.model._meta.verbose_name, |
| 1140 |
"pk": value, |
| 1141 |
"field": self.remote_field.field_name, |
| 1142 |
"value": value, |
| 1143 |
}, # 'pk' is included for backwards compatibility |
| 1144 |
) |
| 1145 |
|
| 1146 |
def resolve_related_fields(self): |
| 1147 |
related_fields = super().resolve_related_fields() |
| 1148 |
for from_field, to_field in related_fields: |
| 1149 |
if ( |
| 1150 |
to_field |
| 1151 |
and to_field.model != self.remote_field.model._meta.concrete_model |
| 1152 |
): |
| 1153 |
raise exceptions.FieldError( |
| 1154 |
"'%s.%s' refers to field '%s' which is not local to model " |
| 1155 |
"'%s'." |
| 1156 |
% ( |
| 1157 |
self.model._meta.label, |
| 1158 |
self.name, |
| 1159 |
to_field.name, |
| 1160 |
self.remote_field.model._meta.concrete_model._meta.label, |
| 1161 |
) |
| 1162 |
) |
| 1163 |
return related_fields |
| 1164 |
|
| 1165 |
def get_attname(self): |
| 1166 |
return "%s_id" % self.name |
| 1167 |
|
| 1168 |
def get_attname_column(self): |
| 1169 |
attname = self.get_attname() |
| 1170 |
column = self.db_column or attname |
| 1171 |
return attname, column |
| 1172 |
|
| 1173 |
def get_default(self): |
| 1174 |
"""Return the to_field if the default value is an object.""" |
| 1175 |
field_default = super().get_default() |
| 1176 |
if isinstance(field_default, self.remote_field.model): |
| 1177 |
return getattr(field_default, self.target_field.attname) |
| 1178 |
return field_default |
| 1179 |
|
| 1180 |
def get_db_prep_save(self, value, connection): |
| 1181 |
if value is None or ( |
| 1182 |
value == "" |
| 1183 |
and ( |
| 1184 |
not self.target_field.empty_strings_allowed |
| 1185 |
or connection.features.interprets_empty_strings_as_nulls |
| 1186 |
) |
| 1187 |
): |
| 1188 |
return None |
| 1189 |
else: |
| 1190 |
return self.target_field.get_db_prep_save(value, connection=connection) |
| 1191 |
|
| 1192 |
def get_db_prep_value(self, value, connection, prepared=False): |
| 1193 |
return self.target_field.get_db_prep_value(value, connection, prepared) |
| 1194 |
|
| 1195 |
def get_prep_value(self, value): |
| 1196 |
return self.target_field.get_prep_value(value) |
| 1197 |
|
| 1198 |
def contribute_to_related_class(self, cls, related): |
| 1199 |
super().contribute_to_related_class(cls, related) |
| 1200 |
if self.remote_field.field_name is None: |
| 1201 |
self.remote_field.field_name = cls._meta.pk.name |
| 1202 |
|
| 1203 |
def formfield(self, *, using=None, **kwargs): |
| 1204 |
if isinstance(self.remote_field.model, str): |
| 1205 |
raise ValueError( |
| 1206 |
"Cannot create form field for %r yet, because " |
| 1207 |
"its related model %r has not been loaded yet" |
| 1208 |
% (self.name, self.remote_field.model) |
| 1209 |
) |
| 1210 |
return super().formfield( |
| 1211 |
**{ |
| 1212 |
"form_class": forms.ModelChoiceField, |
| 1213 |
"queryset": self.remote_field.model._default_manager.using(using), |
| 1214 |
"to_field_name": self.remote_field.field_name, |
| 1215 |
**kwargs, |
| 1216 |
"blank": self.blank, |
| 1217 |
} |
| 1218 |
) |
| 1219 |
|
| 1220 |
def db_check(self, connection): |
| 1221 |
return None |
| 1222 |
|
| 1223 |
def db_type(self, connection): |
| 1224 |
return self.target_field.rel_db_type(connection=connection) |
| 1225 |
|
| 1226 |
def cast_db_type(self, connection): |
| 1227 |
return self.target_field.cast_db_type(connection=connection) |
| 1228 |
|
| 1229 |
def db_parameters(self, connection): |
| 1230 |
target_db_parameters = self.target_field.db_parameters(connection) |
| 1231 |
return { |
| 1232 |
"type": self.db_type(connection), |
| 1233 |
"check": self.db_check(connection), |
| 1234 |
"collation": target_db_parameters.get("collation"), |
| 1235 |
} |
| 1236 |
|
| 1237 |
def convert_empty_strings(self, value, expression, connection): |
| 1238 |
if (not value) and isinstance(value, str): |
| 1239 |
return None |
| 1240 |
return value |
| 1241 |
|
| 1242 |
def get_db_converters(self, connection): |
| 1243 |
converters = super().get_db_converters(connection) |
| 1244 |
if connection.features.interprets_empty_strings_as_nulls: |
| 1245 |
converters += [self.convert_empty_strings] |
| 1246 |
return converters |
| 1247 |
|
| 1248 |
def get_col(self, alias, output_field=None): |
| 1249 |
if output_field is None: |
| 1250 |
output_field = self.target_field |
| 1251 |
while isinstance(output_field, ForeignKey): |
| 1252 |
output_field = output_field.target_field |
| 1253 |
if output_field is self: |
| 1254 |
raise ValueError("Cannot resolve output_field.") |
| 1255 |
return super().get_col(alias, output_field) |
| 1256 |
|
| 1257 |
|
| 1258 |
class OneToOneField(ForeignKey): |
| 1259 |
""" |
| 1260 |
A OneToOneField is essentially the same as a ForeignKey, with the exception |
| 1261 |
that it always carries a "unique" constraint with it and the reverse |
| 1262 |
relation always returns the object pointed to (since there will only ever |
| 1263 |
be one), rather than returning a list. |
| 1264 |
""" |
| 1265 |
|
| 1266 |
# Field flags |
| 1267 |
many_to_many = False |
| 1268 |
many_to_one = False |
| 1269 |
one_to_many = False |
| 1270 |
one_to_one = True |
| 1271 |
|
| 1272 |
related_accessor_class = ReverseOneToOneDescriptor |
| 1273 |
forward_related_accessor_class = ForwardOneToOneDescriptor |
| 1274 |
rel_class = OneToOneRel |
| 1275 |
|
| 1276 |
description = _("One-to-one relationship") |
| 1277 |
|
| 1278 |
def __init__(self, to, on_delete, to_field=None, **kwargs): |
| 1279 |
kwargs["unique"] = True |
| 1280 |
super().__init__(to, on_delete, to_field=to_field, **kwargs) |
| 1281 |
|
| 1282 |
def deconstruct(self): |
| 1283 |
name, path, args, kwargs = super().deconstruct() |
| 1284 |
if "unique" in kwargs: |
| 1285 |
del kwargs["unique"] |
| 1286 |
return name, path, args, kwargs |
| 1287 |
|
| 1288 |
def formfield(self, **kwargs): |
| 1289 |
if self.remote_field.parent_link: |
| 1290 |
return None |
| 1291 |
return super().formfield(**kwargs) |
| 1292 |
|
| 1293 |
def save_form_data(self, instance, data): |
| 1294 |
if isinstance(data, self.remote_field.model): |
| 1295 |
setattr(instance, self.name, data) |
| 1296 |
else: |
| 1297 |
setattr(instance, self.attname, data) |
| 1298 |
# Remote field object must be cleared otherwise Model.save() |
| 1299 |
# will reassign attname using the related object pk. |
| 1300 |
if data is None: |
| 1301 |
setattr(instance, self.name, data) |
| 1302 |
|
| 1303 |
def _check_unique(self, **kwargs): |
| 1304 |
# Override ForeignKey since check isn't applicable here. |
| 1305 |
return [] |
| 1306 |
|
| 1307 |
|
| 1308 |
def create_many_to_many_intermediary_model(field, klass): |
| 1309 |
from django.db import models |
| 1310 |
|
| 1311 |
def set_managed(model, related, through): |
| 1312 |
through._meta.managed = model._meta.managed or related._meta.managed |
| 1313 |
|
| 1314 |
to_model = resolve_relation(klass, field.remote_field.model) |
| 1315 |
name = "%s_%s" % (klass._meta.object_name, field.name) |
| 1316 |
lazy_related_operation(set_managed, klass, to_model, name) |
| 1317 |
|
| 1318 |
to = make_model_tuple(to_model)[1] |
| 1319 |
from_ = klass._meta.model_name |
| 1320 |
if to == from_: |
| 1321 |
to = "to_%s" % to |
| 1322 |
from_ = "from_%s" % from_ |
| 1323 |
|
| 1324 |
meta = type( |
| 1325 |
"Meta", |
| 1326 |
(), |
| 1327 |
{ |
| 1328 |
"db_table": field._get_m2m_db_table(klass._meta), |
| 1329 |
"auto_created": klass, |
| 1330 |
"app_label": klass._meta.app_label, |
| 1331 |
"db_tablespace": klass._meta.db_tablespace, |
| 1332 |
"unique_together": (from_, to), |
| 1333 |
"verbose_name": _("%(from)s-%(to)s relationship") |
| 1334 |
% {"from": from_, "to": to}, |
| 1335 |
"verbose_name_plural": _("%(from)s-%(to)s relationships") |
| 1336 |
% {"from": from_, "to": to}, |
| 1337 |
"apps": field.model._meta.apps, |
| 1338 |
}, |
| 1339 |
) |
| 1340 |
# Construct and return the new class. |
| 1341 |
return type( |
| 1342 |
name, |
| 1343 |
(models.Model,), |
| 1344 |
{ |
| 1345 |
"Meta": meta, |
| 1346 |
"__module__": klass.__module__, |
| 1347 |
from_: models.ForeignKey( |
| 1348 |
klass, |
| 1349 |
related_name="%s+" % name, |
| 1350 |
db_tablespace=field.db_tablespace, |
| 1351 |
db_constraint=field.remote_field.db_constraint, |
| 1352 |
on_delete=CASCADE, |
| 1353 |
), |
| 1354 |
to: models.ForeignKey( |
| 1355 |
to_model, |
| 1356 |
related_name="%s+" % name, |
| 1357 |
db_tablespace=field.db_tablespace, |
| 1358 |
db_constraint=field.remote_field.db_constraint, |
| 1359 |
on_delete=CASCADE, |
| 1360 |
), |
| 1361 |
}, |
| 1362 |
) |
| 1363 |
|
| 1364 |
|
| 1365 |
class ManyToManyField(RelatedField): |
| 1366 |
""" |
| 1367 |
Provide a many-to-many relation by using an intermediary model that |
| 1368 |
holds two ForeignKey fields pointed at the two sides of the relation. |
| 1369 |
|
| 1370 |
Unless a ``through`` model was provided, ManyToManyField will use the |
| 1371 |
create_many_to_many_intermediary_model factory to automatically generate |
| 1372 |
the intermediary model. |
| 1373 |
""" |
| 1374 |
|
| 1375 |
# Field flags |
| 1376 |
many_to_many = True |
| 1377 |
many_to_one = False |
| 1378 |
one_to_many = False |
| 1379 |
one_to_one = False |
| 1380 |
|
| 1381 |
rel_class = ManyToManyRel |
| 1382 |
|
| 1383 |
description = _("Many-to-many relationship") |
| 1384 |
|
| 1385 |
def __init__( |
| 1386 |
self, |
| 1387 |
to, |
| 1388 |
related_name=None, |
| 1389 |
related_query_name=None, |
| 1390 |
limit_choices_to=None, |
| 1391 |
symmetrical=None, |
| 1392 |
through=None, |
| 1393 |
through_fields=None, |
| 1394 |
db_constraint=True, |
| 1395 |
db_table=None, |
| 1396 |
swappable=True, |
| 1397 |
**kwargs, |
| 1398 |
): |
| 1399 |
try: |
| 1400 |
to._meta |
| 1401 |
except AttributeError: |
| 1402 |
if not isinstance(to, str): |
| 1403 |
raise TypeError( |
| 1404 |
"%s(%r) is invalid. First parameter to ManyToManyField " |
| 1405 |
"must be either a model, a model name, or the string %r" |
| 1406 |
% ( |
| 1407 |
self.__class__.__name__, |
| 1408 |
to, |
| 1409 |
RECURSIVE_RELATIONSHIP_CONSTANT, |
| 1410 |
) |
| 1411 |
) |
| 1412 |
|
| 1413 |
if symmetrical is None: |
| 1414 |
symmetrical = to == RECURSIVE_RELATIONSHIP_CONSTANT |
| 1415 |
|
| 1416 |
if through is not None and db_table is not None: |
| 1417 |
raise ValueError( |
| 1418 |
"Cannot specify a db_table if an intermediary model is used." |
| 1419 |
) |
| 1420 |
|
| 1421 |
kwargs["rel"] = self.rel_class( |
| 1422 |
self, |
| 1423 |
to, |
| 1424 |
related_name=related_name, |
| 1425 |
related_query_name=related_query_name, |
| 1426 |
limit_choices_to=limit_choices_to, |
| 1427 |
symmetrical=symmetrical, |
| 1428 |
through=through, |
| 1429 |
through_fields=through_fields, |
| 1430 |
db_constraint=db_constraint, |
| 1431 |
) |
| 1432 |
self.has_null_arg = "null" in kwargs |
| 1433 |
|
| 1434 |
super().__init__( |
| 1435 |
related_name=related_name, |
| 1436 |
related_query_name=related_query_name, |
| 1437 |
limit_choices_to=limit_choices_to, |
| 1438 |
**kwargs, |
| 1439 |
) |
| 1440 |
|
| 1441 |
self.db_table = db_table |
| 1442 |
self.swappable = swappable |
| 1443 |
|
| 1444 |
def check(self, **kwargs): |
| 1445 |
return [ |
| 1446 |
*super().check(**kwargs), |
| 1447 |
*self._check_unique(**kwargs), |
| 1448 |
*self._check_relationship_model(**kwargs), |
| 1449 |
*self._check_ignored_options(**kwargs), |
| 1450 |
*self._check_table_uniqueness(**kwargs), |
| 1451 |
] |
| 1452 |
|
| 1453 |
def _check_unique(self, **kwargs): |
| 1454 |
if self.unique: |
| 1455 |
return [ |
| 1456 |
checks.Error( |
| 1457 |
"ManyToManyFields cannot be unique.", |
| 1458 |
obj=self, |
| 1459 |
id="fields.E330", |
| 1460 |
) |
| 1461 |
] |
| 1462 |
return [] |
| 1463 |
|
| 1464 |
def _check_ignored_options(self, **kwargs): |
| 1465 |
warnings = [] |
| 1466 |
|
| 1467 |
if self.has_null_arg: |
| 1468 |
warnings.append( |
| 1469 |
checks.Warning( |
| 1470 |
"null has no effect on ManyToManyField.", |
| 1471 |
obj=self, |
| 1472 |
id="fields.W340", |
| 1473 |
) |
| 1474 |
) |
| 1475 |
|
| 1476 |
if self._validators: |
| 1477 |
warnings.append( |
| 1478 |
checks.Warning( |
| 1479 |
"ManyToManyField does not support validators.", |
| 1480 |
obj=self, |
| 1481 |
id="fields.W341", |
| 1482 |
) |
| 1483 |
) |
| 1484 |
if self.remote_field.symmetrical and self._related_name: |
| 1485 |
warnings.append( |
| 1486 |
checks.Warning( |
| 1487 |
"related_name has no effect on ManyToManyField " |
| 1488 |
'with a symmetrical relationship, e.g. to "self".', |
| 1489 |
obj=self, |
| 1490 |
id="fields.W345", |
| 1491 |
) |
| 1492 |
) |
| 1493 |
if self.db_comment: |
| 1494 |
warnings.append( |
| 1495 |
checks.Warning( |
| 1496 |
"db_comment has no effect on ManyToManyField.", |
| 1497 |
obj=self, |
| 1498 |
id="fields.W346", |
| 1499 |
) |
| 1500 |
) |
| 1501 |
|
| 1502 |
return warnings |
| 1503 |
|
| 1504 |
def _check_relationship_model(self, from_model=None, **kwargs): |
| 1505 |
from django.db.models.fields.composite import CompositePrimaryKey |
| 1506 |
|
| 1507 |
if hasattr(self.remote_field.through, "_meta"): |
| 1508 |
qualified_model_name = "%s.%s" % ( |
| 1509 |
self.remote_field.through._meta.app_label, |
| 1510 |
self.remote_field.through.__name__, |
| 1511 |
) |
| 1512 |
else: |
| 1513 |
qualified_model_name = self.remote_field.through |
| 1514 |
|
| 1515 |
errors = [] |
| 1516 |
|
| 1517 |
if self.remote_field.through not in self.opts.apps.get_models( |
| 1518 |
include_auto_created=True |
| 1519 |
): |
| 1520 |
# The relationship model is not installed. |
| 1521 |
errors.append( |
| 1522 |
checks.Error( |
| 1523 |
"Field specifies a many-to-many relation through model " |
| 1524 |
"'%s', which has not been installed." % qualified_model_name, |
| 1525 |
obj=self, |
| 1526 |
id="fields.E331", |
| 1527 |
) |
| 1528 |
) |
| 1529 |
|
| 1530 |
else: |
| 1531 |
assert from_model is not None, ( |
| 1532 |
"ManyToManyField with intermediate " |
| 1533 |
"tables cannot be checked if you don't pass the model " |
| 1534 |
"where the field is attached to." |
| 1535 |
) |
| 1536 |
# Set some useful local variables |
| 1537 |
to_model = resolve_relation(from_model, self.remote_field.model) |
| 1538 |
from_model_name = from_model._meta.object_name |
| 1539 |
if isinstance(to_model, str): |
| 1540 |
to_model_name = to_model |
| 1541 |
else: |
| 1542 |
to_model_name = to_model._meta.object_name |
| 1543 |
if self.remote_field.through_fields is None and not isinstance( |
| 1544 |
to_model, str |
| 1545 |
): |
| 1546 |
model_name = None |
| 1547 |
if isinstance(to_model._meta.pk, CompositePrimaryKey): |
| 1548 |
model_name = self.remote_field.model._meta.object_name |
| 1549 |
elif isinstance(from_model._meta.pk, CompositePrimaryKey): |
| 1550 |
model_name = from_model_name |
| 1551 |
if model_name: |
| 1552 |
errors.append( |
| 1553 |
checks.Error( |
| 1554 |
f"Field defines a relation involving model {model_name!r} " |
| 1555 |
"which has a CompositePrimaryKey and such relations are " |
| 1556 |
"not supported.", |
| 1557 |
obj=self, |
| 1558 |
id="fields.E347", |
| 1559 |
) |
| 1560 |
) |
| 1561 |
relationship_model_name = self.remote_field.through._meta.object_name |
| 1562 |
self_referential = from_model == to_model |
| 1563 |
# Count foreign keys in intermediate model |
| 1564 |
if self_referential: |
| 1565 |
seen_self = sum( |
| 1566 |
from_model == getattr(field.remote_field, "model", None) |
| 1567 |
for field in self.remote_field.through._meta.fields |
| 1568 |
) |
| 1569 |
|
| 1570 |
if seen_self > 2 and not self.remote_field.through_fields: |
| 1571 |
errors.append( |
| 1572 |
checks.Error( |
| 1573 |
"The model is used as an intermediate model by " |
| 1574 |
"'%s', but it has more than two foreign keys " |
| 1575 |
"to '%s', which is ambiguous. You must specify " |
| 1576 |
"which two foreign keys Django should use via the " |
| 1577 |
"through_fields keyword argument." |
| 1578 |
% (self, from_model_name), |
| 1579 |
hint=( |
| 1580 |
"Use through_fields to specify which two foreign keys " |
| 1581 |
"Django should use." |
| 1582 |
), |
| 1583 |
obj=self.remote_field.through, |
| 1584 |
id="fields.E333", |
| 1585 |
) |
| 1586 |
) |
| 1587 |
|
| 1588 |
else: |
| 1589 |
# Count foreign keys in relationship model |
| 1590 |
seen_from = sum( |
| 1591 |
from_model == getattr(field.remote_field, "model", None) |
| 1592 |
for field in self.remote_field.through._meta.fields |
| 1593 |
) |
| 1594 |
seen_to = sum( |
| 1595 |
to_model == getattr(field.remote_field, "model", None) |
| 1596 |
for field in self.remote_field.through._meta.fields |
| 1597 |
) |
| 1598 |
|
| 1599 |
if seen_from > 1 and not self.remote_field.through_fields: |
| 1600 |
errors.append( |
| 1601 |
checks.Error( |
| 1602 |
( |
| 1603 |
"The model is used as an intermediate model by " |
| 1604 |
"'%s', but it has more than one foreign key " |
| 1605 |
"from '%s', which is ambiguous. You must specify " |
| 1606 |
"which foreign key Django should use via the " |
| 1607 |
"through_fields keyword argument." |
| 1608 |
) |
| 1609 |
% (self, from_model_name), |
| 1610 |
hint=( |
| 1611 |
"If you want to create a recursive relationship, " |
| 1612 |
'use ManyToManyField("%s", through="%s").' |
| 1613 |
) |
| 1614 |
% ( |
| 1615 |
RECURSIVE_RELATIONSHIP_CONSTANT, |
| 1616 |
relationship_model_name, |
| 1617 |
), |
| 1618 |
obj=self, |
| 1619 |
id="fields.E334", |
| 1620 |
) |
| 1621 |
) |
| 1622 |
|
| 1623 |
if seen_to > 1 and not self.remote_field.through_fields: |
| 1624 |
errors.append( |
| 1625 |
checks.Error( |
| 1626 |
"The model is used as an intermediate model by " |
| 1627 |
"'%s', but it has more than one foreign key " |
| 1628 |
"to '%s', which is ambiguous. You must specify " |
| 1629 |
"which foreign key Django should use via the " |
| 1630 |
"through_fields keyword argument." % (self, to_model_name), |
| 1631 |
hint=( |
| 1632 |
"If you want to create a recursive relationship, " |
| 1633 |
'use ManyToManyField("%s", through="%s").' |
| 1634 |
) |
| 1635 |
% ( |
| 1636 |
RECURSIVE_RELATIONSHIP_CONSTANT, |
| 1637 |
relationship_model_name, |
| 1638 |
), |
| 1639 |
obj=self, |
| 1640 |
id="fields.E335", |
| 1641 |
) |
| 1642 |
) |
| 1643 |
|
| 1644 |
if seen_from == 0 or seen_to == 0: |
| 1645 |
errors.append( |
| 1646 |
checks.Error( |
| 1647 |
"The model is used as an intermediate model by " |
| 1648 |
"'%s', but it does not have a foreign key to '%s' or '%s'." |
| 1649 |
% (self, from_model_name, to_model_name), |
| 1650 |
obj=self.remote_field.through, |
| 1651 |
id="fields.E336", |
| 1652 |
) |
| 1653 |
) |
| 1654 |
|
| 1655 |
# Validate `through_fields`. |
| 1656 |
if self.remote_field.through_fields is not None: |
| 1657 |
# Validate that we're given an iterable of at least two items |
| 1658 |
# and that none of them is "falsy". |
| 1659 |
if not ( |
| 1660 |
len(self.remote_field.through_fields) >= 2 |
| 1661 |
and self.remote_field.through_fields[0] |
| 1662 |
and self.remote_field.through_fields[1] |
| 1663 |
): |
| 1664 |
errors.append( |
| 1665 |
checks.Error( |
| 1666 |
"Field specifies 'through_fields' but does not provide " |
| 1667 |
"the names of the two link fields that should be used " |
| 1668 |
"for the relation through model '%s'." % qualified_model_name, |
| 1669 |
hint=( |
| 1670 |
"Make sure you specify 'through_fields' as " |
| 1671 |
"through_fields=('field1', 'field2')" |
| 1672 |
), |
| 1673 |
obj=self, |
| 1674 |
id="fields.E337", |
| 1675 |
) |
| 1676 |
) |
| 1677 |
|
| 1678 |
# Validate the given through fields -- they should be actual |
| 1679 |
# fields on the through model, and also be foreign keys to the |
| 1680 |
# expected models. |
| 1681 |
else: |
| 1682 |
assert from_model is not None, ( |
| 1683 |
"ManyToManyField with intermediate " |
| 1684 |
"tables cannot be checked if you don't pass the model " |
| 1685 |
"where the field is attached to." |
| 1686 |
) |
| 1687 |
|
| 1688 |
source, through, target = ( |
| 1689 |
from_model, |
| 1690 |
self.remote_field.through, |
| 1691 |
self.remote_field.model, |
| 1692 |
) |
| 1693 |
source_field_name, target_field_name = self.remote_field.through_fields[ |
| 1694 |
:2 |
| 1695 |
] |
| 1696 |
|
| 1697 |
for field_name, related_model in ( |
| 1698 |
(source_field_name, source), |
| 1699 |
(target_field_name, target), |
| 1700 |
): |
| 1701 |
possible_field_names = [] |
| 1702 |
for f in through._meta.fields: |
| 1703 |
if ( |
| 1704 |
hasattr(f, "remote_field") |
| 1705 |
and getattr(f.remote_field, "model", None) == related_model |
| 1706 |
): |
| 1707 |
possible_field_names.append(f.name) |
| 1708 |
if possible_field_names: |
| 1709 |
hint = ( |
| 1710 |
"Did you mean one of the following foreign keys to '%s': " |
| 1711 |
"%s?" |
| 1712 |
% ( |
| 1713 |
related_model._meta.object_name, |
| 1714 |
", ".join(possible_field_names), |
| 1715 |
) |
| 1716 |
) |
| 1717 |
else: |
| 1718 |
hint = None |
| 1719 |
|
| 1720 |
try: |
| 1721 |
field = through._meta.get_field(field_name) |
| 1722 |
except exceptions.FieldDoesNotExist: |
| 1723 |
errors.append( |
| 1724 |
checks.Error( |
| 1725 |
"The intermediary model '%s' has no field '%s'." |
| 1726 |
% (qualified_model_name, field_name), |
| 1727 |
hint=hint, |
| 1728 |
obj=self, |
| 1729 |
id="fields.E338", |
| 1730 |
) |
| 1731 |
) |
| 1732 |
else: |
| 1733 |
if not ( |
| 1734 |
hasattr(field, "remote_field") |
| 1735 |
and getattr(field.remote_field, "model", None) |
| 1736 |
== related_model |
| 1737 |
): |
| 1738 |
errors.append( |
| 1739 |
checks.Error( |
| 1740 |
"'%s.%s' is not a foreign key to '%s'." |
| 1741 |
% ( |
| 1742 |
through._meta.object_name, |
| 1743 |
field_name, |
| 1744 |
related_model._meta.object_name, |
| 1745 |
), |
| 1746 |
hint=hint, |
| 1747 |
obj=self, |
| 1748 |
id="fields.E339", |
| 1749 |
) |
| 1750 |
) |
| 1751 |
|
| 1752 |
return errors |
| 1753 |
|
| 1754 |
def _check_table_uniqueness(self, **kwargs): |
| 1755 |
if ( |
| 1756 |
isinstance(self.remote_field.through, str) |
| 1757 |
or not self.remote_field.through._meta.managed |
| 1758 |
): |
| 1759 |
return [] |
| 1760 |
registered_tables = { |
| 1761 |
model._meta.db_table: model |
| 1762 |
for model in self.opts.apps.get_models(include_auto_created=True) |
| 1763 |
if model != self.remote_field.through and model._meta.managed |
| 1764 |
} |
| 1765 |
m2m_db_table = self.m2m_db_table() |
| 1766 |
model = registered_tables.get(m2m_db_table) |
| 1767 |
# The second condition allows multiple m2m relations on a model if |
| 1768 |
# some point to a through model that proxies another through model. |
| 1769 |
if ( |
| 1770 |
model |
| 1771 |
and model._meta.concrete_model |
| 1772 |
!= self.remote_field.through._meta.concrete_model |
| 1773 |
): |
| 1774 |
if model._meta.auto_created: |
| 1775 |
|
| 1776 |
def _get_field_name(model): |
| 1777 |
for field in model._meta.auto_created._meta.many_to_many: |
| 1778 |
if field.remote_field.through is model: |
| 1779 |
return field.name |
| 1780 |
|
| 1781 |
opts = model._meta.auto_created._meta |
| 1782 |
clashing_obj = "%s.%s" % (opts.label, _get_field_name(model)) |
| 1783 |
else: |
| 1784 |
clashing_obj = model._meta.label |
| 1785 |
if settings.DATABASE_ROUTERS: |
| 1786 |
error_class, error_id = checks.Warning, "fields.W344" |
| 1787 |
error_hint = ( |
| 1788 |
"You have configured settings.DATABASE_ROUTERS. Verify " |
| 1789 |
"that the table of %r is correctly routed to a separate " |
| 1790 |
"database." % clashing_obj |
| 1791 |
) |
| 1792 |
else: |
| 1793 |
error_class, error_id = checks.Error, "fields.E340" |
| 1794 |
error_hint = None |
| 1795 |
return [ |
| 1796 |
error_class( |
| 1797 |
"The field's intermediary table '%s' clashes with the " |
| 1798 |
"table name of '%s'." % (m2m_db_table, clashing_obj), |
| 1799 |
obj=self, |
| 1800 |
hint=error_hint, |
| 1801 |
id=error_id, |
| 1802 |
) |
| 1803 |
] |
| 1804 |
return [] |
| 1805 |
|
| 1806 |
def deconstruct(self): |
| 1807 |
name, path, args, kwargs = super().deconstruct() |
| 1808 |
# Handle the simpler arguments. |
| 1809 |
if self.db_table is not None: |
| 1810 |
kwargs["db_table"] = self.db_table |
| 1811 |
if self.remote_field.db_constraint is not True: |
| 1812 |
kwargs["db_constraint"] = self.remote_field.db_constraint |
| 1813 |
# Lowercase model names as they should be treated as case-insensitive. |
| 1814 |
if isinstance(self.remote_field.model, str): |
| 1815 |
if "." in self.remote_field.model: |
| 1816 |
app_label, model_name = self.remote_field.model.split(".") |
| 1817 |
kwargs["to"] = "%s.%s" % (app_label, model_name.lower()) |
| 1818 |
else: |
| 1819 |
kwargs["to"] = self.remote_field.model.lower() |
| 1820 |
else: |
| 1821 |
kwargs["to"] = self.remote_field.model._meta.label_lower |
| 1822 |
if getattr(self.remote_field, "through", None) is not None: |
| 1823 |
if isinstance(self.remote_field.through, str): |
| 1824 |
kwargs["through"] = self.remote_field.through |
| 1825 |
elif not self.remote_field.through._meta.auto_created: |
| 1826 |
kwargs["through"] = self.remote_field.through._meta.label |
| 1827 |
if through_fields := getattr(self.remote_field, "through_fields", None): |
| 1828 |
kwargs["through_fields"] = through_fields |
| 1829 |
# If swappable is True, then see if we're actually pointing to the target |
| 1830 |
# of a swap. |
| 1831 |
swappable_setting = self.swappable_setting |
| 1832 |
if swappable_setting is not None: |
| 1833 |
# If it's already a settings reference, error. |
| 1834 |
if hasattr(kwargs["to"], "setting_name"): |
| 1835 |
if kwargs["to"].setting_name != swappable_setting: |
| 1836 |
raise ValueError( |
| 1837 |
"Cannot deconstruct a ManyToManyField pointing to a " |
| 1838 |
"model that is swapped in place of more than one model " |
| 1839 |
"(%s and %s)" % (kwargs["to"].setting_name, swappable_setting) |
| 1840 |
) |
| 1841 |
|
| 1842 |
kwargs["to"] = SettingsReference( |
| 1843 |
kwargs["to"], |
| 1844 |
swappable_setting, |
| 1845 |
) |
| 1846 |
return name, path, args, kwargs |
| 1847 |
|
| 1848 |
def _get_path_info(self, direct=False, filtered_relation=None): |
| 1849 |
"""Called by both direct and indirect m2m traversal.""" |
| 1850 |
int_model = self.remote_field.through |
| 1851 |
linkfield1 = int_model._meta.get_field(self.m2m_field_name()) |
| 1852 |
linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name()) |
| 1853 |
if direct: |
| 1854 |
join1infos = linkfield1.reverse_path_infos |
| 1855 |
if filtered_relation: |
| 1856 |
join2infos = linkfield2.get_path_info(filtered_relation) |
| 1857 |
else: |
| 1858 |
join2infos = linkfield2.path_infos |
| 1859 |
else: |
| 1860 |
join1infos = linkfield2.reverse_path_infos |
| 1861 |
if filtered_relation: |
| 1862 |
join2infos = linkfield1.get_path_info(filtered_relation) |
| 1863 |
else: |
| 1864 |
join2infos = linkfield1.path_infos |
| 1865 |
# Get join infos between the last model of join 1 and the first model |
| 1866 |
# of join 2. Assume the only reason these may differ is due to model |
| 1867 |
# inheritance. |
| 1868 |
join1_final = join1infos[-1].to_opts |
| 1869 |
join2_initial = join2infos[0].from_opts |
| 1870 |
if join1_final is join2_initial: |
| 1871 |
intermediate_infos = [] |
| 1872 |
elif issubclass(join1_final.model, join2_initial.model): |
| 1873 |
intermediate_infos = join1_final.get_path_to_parent(join2_initial.model) |
| 1874 |
else: |
| 1875 |
intermediate_infos = join2_initial.get_path_from_parent(join1_final.model) |
| 1876 |
|
| 1877 |
return [*join1infos, *intermediate_infos, *join2infos] |
| 1878 |
|
| 1879 |
def get_path_info(self, filtered_relation=None): |
| 1880 |
return self._get_path_info(direct=True, filtered_relation=filtered_relation) |
| 1881 |
|
| 1882 |
@cached_property |
| 1883 |
def path_infos(self): |
| 1884 |
return self.get_path_info() |
| 1885 |
|
| 1886 |
def get_reverse_path_info(self, filtered_relation=None): |
| 1887 |
return self._get_path_info(direct=False, filtered_relation=filtered_relation) |
| 1888 |
|
| 1889 |
@cached_property |
| 1890 |
def reverse_path_infos(self): |
| 1891 |
return self.get_reverse_path_info() |
| 1892 |
|
| 1893 |
def _get_m2m_db_table(self, opts): |
| 1894 |
""" |
| 1895 |
Function that can be curried to provide the m2m table name for this |
| 1896 |
relation. |
| 1897 |
""" |
| 1898 |
if self.remote_field.through is not None: |
| 1899 |
return self.remote_field.through._meta.db_table |
| 1900 |
elif self.db_table: |
| 1901 |
return self.db_table |
| 1902 |
else: |
| 1903 |
m2m_table_name = "%s_%s" % (utils.strip_quotes(opts.db_table), self.name) |
| 1904 |
return utils.truncate_name(m2m_table_name, connection.ops.max_name_length()) |
| 1905 |
|
| 1906 |
def _get_m2m_attr(self, related, attr): |
| 1907 |
""" |
| 1908 |
Function that can be curried to provide the source accessor or DB |
| 1909 |
column name for the m2m table. |
| 1910 |
""" |
| 1911 |
cache_attr = "_m2m_%s_cache" % attr |
| 1912 |
if hasattr(self, cache_attr): |
| 1913 |
return getattr(self, cache_attr) |
| 1914 |
if self.remote_field.through_fields is not None: |
| 1915 |
link_field_name = self.remote_field.through_fields[0] |
| 1916 |
else: |
| 1917 |
link_field_name = None |
| 1918 |
for f in self.remote_field.through._meta.fields: |
| 1919 |
if ( |
| 1920 |
f.is_relation |
| 1921 |
and f.remote_field.model == related.related_model |
| 1922 |
and (link_field_name is None or link_field_name == f.name) |
| 1923 |
): |
| 1924 |
setattr(self, cache_attr, getattr(f, attr)) |
| 1925 |
return getattr(self, cache_attr) |
| 1926 |
|
| 1927 |
def _get_m2m_reverse_attr(self, related, attr): |
| 1928 |
""" |
| 1929 |
Function that can be curried to provide the related accessor or DB |
| 1930 |
column name for the m2m table. |
| 1931 |
""" |
| 1932 |
cache_attr = "_m2m_reverse_%s_cache" % attr |
| 1933 |
if hasattr(self, cache_attr): |
| 1934 |
return getattr(self, cache_attr) |
| 1935 |
found = False |
| 1936 |
if self.remote_field.through_fields is not None: |
| 1937 |
link_field_name = self.remote_field.through_fields[1] |
| 1938 |
else: |
| 1939 |
link_field_name = None |
| 1940 |
for f in self.remote_field.through._meta.fields: |
| 1941 |
if f.is_relation and f.remote_field.model == related.model: |
| 1942 |
if link_field_name is None and related.related_model == related.model: |
| 1943 |
# If this is an m2m-intermediate to self, |
| 1944 |
# the first foreign key you find will be |
| 1945 |
# the source column. Keep searching for |
| 1946 |
# the second foreign key. |
| 1947 |
if found: |
| 1948 |
setattr(self, cache_attr, getattr(f, attr)) |
| 1949 |
break |
| 1950 |
else: |
| 1951 |
found = True |
| 1952 |
elif link_field_name is None or link_field_name == f.name: |
| 1953 |
setattr(self, cache_attr, getattr(f, attr)) |
| 1954 |
break |
| 1955 |
return getattr(self, cache_attr) |
| 1956 |
|
| 1957 |
def contribute_to_class(self, cls, name, **kwargs): |
| 1958 |
# To support multiple relations to self, it's useful to have a non-None |
| 1959 |
# related name on symmetrical relations for internal reasons. The |
| 1960 |
# concept doesn't make a lot of sense externally ("you want me to |
| 1961 |
# specify *what* on my non-reversible relation?!"), so we set it up |
| 1962 |
# automatically. The funky name reduces the chance of an accidental |
| 1963 |
# clash. |
| 1964 |
if self.remote_field.symmetrical and ( |
| 1965 |
self.remote_field.model == RECURSIVE_RELATIONSHIP_CONSTANT |
| 1966 |
or self.remote_field.model == cls._meta.object_name |
| 1967 |
): |
| 1968 |
self.remote_field.related_name = "%s_rel_+" % name |
| 1969 |
elif self.remote_field.hidden: |
| 1970 |
# If the backwards relation is disabled, replace the original |
| 1971 |
# related_name with one generated from the m2m field name. Django |
| 1972 |
# still uses backwards relations internally and we need to avoid |
| 1973 |
# clashes between multiple m2m fields with related_name == '+'. |
| 1974 |
self.remote_field.related_name = "_%s_%s_%s_+" % ( |
| 1975 |
cls._meta.app_label, |
| 1976 |
cls.__name__.lower(), |
| 1977 |
name, |
| 1978 |
) |
| 1979 |
|
| 1980 |
super().contribute_to_class(cls, name, **kwargs) |
| 1981 |
|
| 1982 |
# The intermediate m2m model is not auto created if: |
| 1983 |
# 1) There is a manually specified intermediate, or |
| 1984 |
# 2) The class owning the m2m field is abstract. |
| 1985 |
# 3) The class owning the m2m field has been swapped out. |
| 1986 |
if not cls._meta.abstract: |
| 1987 |
if self.remote_field.through: |
| 1988 |
|
| 1989 |
def resolve_through_model(_, model, field): |
| 1990 |
field.remote_field.through = model |
| 1991 |
|
| 1992 |
lazy_related_operation( |
| 1993 |
resolve_through_model, cls, self.remote_field.through, field=self |
| 1994 |
) |
| 1995 |
elif not cls._meta.swapped: |
| 1996 |
self.remote_field.through = create_many_to_many_intermediary_model( |
| 1997 |
self, cls |
| 1998 |
) |
| 1999 |
|
| 2000 |
# Add the descriptor for the m2m relation. |
| 2001 |
setattr(cls, self.name, ManyToManyDescriptor(self.remote_field, reverse=False)) |
| 2002 |
|
| 2003 |
# Set up the accessor for the m2m table name for the relation. |
| 2004 |
self.m2m_db_table = partial(self._get_m2m_db_table, cls._meta) |
| 2005 |
|
| 2006 |
def contribute_to_related_class(self, cls, related): |
| 2007 |
# Internal M2Ms (i.e., those with a related name ending with '+') |
| 2008 |
# and swapped models don't get a related descriptor. |
| 2009 |
if not self.remote_field.hidden and not related.related_model._meta.swapped: |
| 2010 |
setattr( |
| 2011 |
cls, |
| 2012 |
related.accessor_name, |
| 2013 |
ManyToManyDescriptor(self.remote_field, reverse=True), |
| 2014 |
) |
| 2015 |
|
| 2016 |
# Set up the accessors for the column names on the m2m table. |
| 2017 |
self.m2m_column_name = partial(self._get_m2m_attr, related, "column") |
| 2018 |
self.m2m_reverse_name = partial(self._get_m2m_reverse_attr, related, "column") |
| 2019 |
|
| 2020 |
self.m2m_field_name = partial(self._get_m2m_attr, related, "name") |
| 2021 |
self.m2m_reverse_field_name = partial( |
| 2022 |
self._get_m2m_reverse_attr, related, "name" |
| 2023 |
) |
| 2024 |
|
| 2025 |
get_m2m_rel = partial(self._get_m2m_attr, related, "remote_field") |
| 2026 |
self.m2m_target_field_name = lambda: get_m2m_rel().field_name |
| 2027 |
get_m2m_reverse_rel = partial( |
| 2028 |
self._get_m2m_reverse_attr, related, "remote_field" |
| 2029 |
) |
| 2030 |
self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name |
| 2031 |
|
| 2032 |
def set_attributes_from_rel(self): |
| 2033 |
pass |
| 2034 |
|
| 2035 |
def value_from_object(self, obj): |
| 2036 |
return list(getattr(obj, self.attname).all()) if obj._is_pk_set() else [] |
| 2037 |
|
| 2038 |
def save_form_data(self, instance, data): |
| 2039 |
getattr(instance, self.attname).set(data) |
| 2040 |
|
| 2041 |
def formfield(self, *, using=None, **kwargs): |
| 2042 |
defaults = { |
| 2043 |
"form_class": forms.ModelMultipleChoiceField, |
| 2044 |
"queryset": self.remote_field.model._default_manager.using(using), |
| 2045 |
**kwargs, |
| 2046 |
} |
| 2047 |
# If initial is passed in, it's a list of related objects, but the |
| 2048 |
# MultipleChoiceField takes a list of IDs. |
| 2049 |
if defaults.get("initial") is not None: |
| 2050 |
initial = defaults["initial"] |
| 2051 |
if callable(initial): |
| 2052 |
initial = initial() |
| 2053 |
defaults["initial"] = [i.pk for i in initial] |
| 2054 |
return super().formfield(**defaults) |
| 2055 |
|
| 2056 |
def db_check(self, connection): |
| 2057 |
return None |
| 2058 |
|
| 2059 |
def db_type(self, connection): |
| 2060 |
# A ManyToManyField is not represented by a single column, |
| 2061 |
# so return None. |
| 2062 |
return None |
| 2063 |
|
| 2064 |
def db_parameters(self, connection): |
| 2065 |
return {"type": None, "check": None} |