| 1 |
""" |
| 2 |
"Rel objects" for related fields. |
| 3 |
|
| 4 |
"Rel objects" (for lack of a better name) carry information about the relation |
| 5 |
modeled by a related field and provide some utility functions. They're stored |
| 6 |
in the ``remote_field`` attribute of the field. |
| 7 |
|
| 8 |
They also act as reverse fields for the purposes of the Meta API because |
| 9 |
they're the closest concept currently available. |
| 10 |
""" |
| 11 |
|
| 12 |
import warnings |
| 13 |
|
| 14 |
from django.core import exceptions |
| 15 |
from django.utils.deprecation import RemovedInDjango60Warning |
| 16 |
from django.utils.functional import cached_property |
| 17 |
from django.utils.hashable import make_hashable |
| 18 |
|
| 19 |
from . import BLANK_CHOICE_DASH |
| 20 |
from .mixins import FieldCacheMixin |
| 21 |
|
| 22 |
|
| 23 |
class ForeignObjectRel(FieldCacheMixin): |
| 24 |
""" |
| 25 |
Used by ForeignObject to store information about the relation. |
| 26 |
|
| 27 |
``_meta.get_fields()`` returns this class to provide access to the field |
| 28 |
flags for the reverse relation. |
| 29 |
""" |
| 30 |
|
| 31 |
# Field flags |
| 32 |
auto_created = True |
| 33 |
concrete = False |
| 34 |
editable = False |
| 35 |
is_relation = True |
| 36 |
|
| 37 |
# Reverse relations are always nullable (Django can't enforce that a |
| 38 |
# foreign key on the related model points to this model). |
| 39 |
null = True |
| 40 |
empty_strings_allowed = False |
| 41 |
|
| 42 |
def __init__( |
| 43 |
self, |
| 44 |
field, |
| 45 |
to, |
| 46 |
related_name=None, |
| 47 |
related_query_name=None, |
| 48 |
limit_choices_to=None, |
| 49 |
parent_link=False, |
| 50 |
on_delete=None, |
| 51 |
): |
| 52 |
self.field = field |
| 53 |
self.model = to |
| 54 |
self.related_name = related_name |
| 55 |
self.related_query_name = related_query_name |
| 56 |
self.limit_choices_to = {} if limit_choices_to is None else limit_choices_to |
| 57 |
self.parent_link = parent_link |
| 58 |
self.on_delete = on_delete |
| 59 |
|
| 60 |
self.symmetrical = False |
| 61 |
self.multiple = True |
| 62 |
|
| 63 |
# Some of the following cached_properties can't be initialized in |
| 64 |
# __init__ as the field doesn't have its model yet. Calling these methods |
| 65 |
# before field.contribute_to_class() has been called will result in |
| 66 |
# AttributeError |
| 67 |
@cached_property |
| 68 |
def hidden(self): |
| 69 |
"""Should the related object be hidden?""" |
| 70 |
return bool(self.related_name) and self.related_name[-1] == "+" |
| 71 |
|
| 72 |
@cached_property |
| 73 |
def name(self): |
| 74 |
return self.field.related_query_name() |
| 75 |
|
| 76 |
@property |
| 77 |
def remote_field(self): |
| 78 |
return self.field |
| 79 |
|
| 80 |
@property |
| 81 |
def target_field(self): |
| 82 |
""" |
| 83 |
When filtering against this relation, return the field on the remote |
| 84 |
model against which the filtering should happen. |
| 85 |
""" |
| 86 |
target_fields = self.path_infos[-1].target_fields |
| 87 |
if len(target_fields) > 1: |
| 88 |
raise exceptions.FieldError( |
| 89 |
"Can't use target_field for multicolumn relations." |
| 90 |
) |
| 91 |
return target_fields[0] |
| 92 |
|
| 93 |
@cached_property |
| 94 |
def related_model(self): |
| 95 |
if not self.field.model: |
| 96 |
raise AttributeError( |
| 97 |
"This property can't be accessed before self.field.contribute_to_class " |
| 98 |
"has been called." |
| 99 |
) |
| 100 |
return self.field.model |
| 101 |
|
| 102 |
@cached_property |
| 103 |
def many_to_many(self): |
| 104 |
return self.field.many_to_many |
| 105 |
|
| 106 |
@cached_property |
| 107 |
def many_to_one(self): |
| 108 |
return self.field.one_to_many |
| 109 |
|
| 110 |
@cached_property |
| 111 |
def one_to_many(self): |
| 112 |
return self.field.many_to_one |
| 113 |
|
| 114 |
@cached_property |
| 115 |
def one_to_one(self): |
| 116 |
return self.field.one_to_one |
| 117 |
|
| 118 |
def get_lookup(self, lookup_name): |
| 119 |
return self.field.get_lookup(lookup_name) |
| 120 |
|
| 121 |
def get_lookups(self): |
| 122 |
return self.field.get_lookups() |
| 123 |
|
| 124 |
def get_transform(self, name): |
| 125 |
return self.field.get_transform(name) |
| 126 |
|
| 127 |
def get_internal_type(self): |
| 128 |
return self.field.get_internal_type() |
| 129 |
|
| 130 |
@property |
| 131 |
def db_type(self): |
| 132 |
return self.field.db_type |
| 133 |
|
| 134 |
def __repr__(self): |
| 135 |
return "<%s: %s.%s>" % ( |
| 136 |
type(self).__name__, |
| 137 |
self.related_model._meta.app_label, |
| 138 |
self.related_model._meta.model_name, |
| 139 |
) |
| 140 |
|
| 141 |
@property |
| 142 |
def identity(self): |
| 143 |
return ( |
| 144 |
self.field, |
| 145 |
self.model, |
| 146 |
self.related_name, |
| 147 |
self.related_query_name, |
| 148 |
make_hashable(self.limit_choices_to), |
| 149 |
self.parent_link, |
| 150 |
self.on_delete, |
| 151 |
self.symmetrical, |
| 152 |
self.multiple, |
| 153 |
) |
| 154 |
|
| 155 |
def __eq__(self, other): |
| 156 |
if not isinstance(other, self.__class__): |
| 157 |
return NotImplemented |
| 158 |
return self.identity == other.identity |
| 159 |
|
| 160 |
def __hash__(self): |
| 161 |
return hash(self.identity) |
| 162 |
|
| 163 |
def __getstate__(self): |
| 164 |
state = self.__dict__.copy() |
| 165 |
# Delete the path_infos cached property because it can be recalculated |
| 166 |
# at first invocation after deserialization. The attribute must be |
| 167 |
# removed because subclasses like ManyToOneRel may have a PathInfo |
| 168 |
# which contains an intermediate M2M table that's been dynamically |
| 169 |
# created and doesn't exist in the .models module. |
| 170 |
# This is a reverse relation, so there is no reverse_path_infos to |
| 171 |
# delete. |
| 172 |
state.pop("path_infos", None) |
| 173 |
return state |
| 174 |
|
| 175 |
def get_choices( |
| 176 |
self, |
| 177 |
include_blank=True, |
| 178 |
blank_choice=BLANK_CHOICE_DASH, |
| 179 |
limit_choices_to=None, |
| 180 |
ordering=(), |
| 181 |
): |
| 182 |
""" |
| 183 |
Return choices with a default blank choices included, for use |
| 184 |
as <select> choices for this field. |
| 185 |
|
| 186 |
Analog of django.db.models.fields.Field.get_choices(), provided |
| 187 |
initially for utilization by RelatedFieldListFilter. |
| 188 |
""" |
| 189 |
limit_choices_to = limit_choices_to or self.limit_choices_to |
| 190 |
qs = self.related_model._default_manager.complex_filter(limit_choices_to) |
| 191 |
if ordering: |
| 192 |
qs = qs.order_by(*ordering) |
| 193 |
return (blank_choice if include_blank else []) + [(x.pk, str(x)) for x in qs] |
| 194 |
|
| 195 |
def get_joining_columns(self): |
| 196 |
warnings.warn( |
| 197 |
"ForeignObjectRel.get_joining_columns() is deprecated. Use " |
| 198 |
"get_joining_fields() instead.", |
| 199 |
RemovedInDjango60Warning, |
| 200 |
stacklevel=2, |
| 201 |
) |
| 202 |
return self.field.get_reverse_joining_columns() |
| 203 |
|
| 204 |
def get_joining_fields(self): |
| 205 |
return self.field.get_reverse_joining_fields() |
| 206 |
|
| 207 |
def get_extra_restriction(self, alias, related_alias): |
| 208 |
return self.field.get_extra_restriction(related_alias, alias) |
| 209 |
|
| 210 |
def set_field_name(self): |
| 211 |
""" |
| 212 |
Set the related field's name, this is not available until later stages |
| 213 |
of app loading, so set_field_name is called from |
| 214 |
set_attributes_from_rel() |
| 215 |
""" |
| 216 |
# By default foreign object doesn't relate to any remote field (for |
| 217 |
# example custom multicolumn joins currently have no remote field). |
| 218 |
self.field_name = None |
| 219 |
|
| 220 |
@cached_property |
| 221 |
def accessor_name(self): |
| 222 |
return self.get_accessor_name() |
| 223 |
|
| 224 |
def get_accessor_name(self, model=None): |
| 225 |
# This method encapsulates the logic that decides what name to give an |
| 226 |
# accessor descriptor that retrieves related many-to-one or |
| 227 |
# many-to-many objects. It uses the lowercased object_name + "_set", |
| 228 |
# but this can be overridden with the "related_name" option. Due to |
| 229 |
# backwards compatibility ModelForms need to be able to provide an |
| 230 |
# alternate model. See BaseInlineFormSet.get_default_prefix(). |
| 231 |
opts = model._meta if model else self.related_model._meta |
| 232 |
model = model or self.related_model |
| 233 |
if self.multiple: |
| 234 |
# If this is a symmetrical m2m relation on self, there is no |
| 235 |
# reverse accessor. |
| 236 |
if self.symmetrical and model == self.model: |
| 237 |
return None |
| 238 |
if self.related_name: |
| 239 |
return self.related_name |
| 240 |
return opts.model_name + ("_set" if self.multiple else "") |
| 241 |
|
| 242 |
def get_path_info(self, filtered_relation=None): |
| 243 |
if filtered_relation: |
| 244 |
return self.field.get_reverse_path_info(filtered_relation) |
| 245 |
else: |
| 246 |
return self.field.reverse_path_infos |
| 247 |
|
| 248 |
@cached_property |
| 249 |
def path_infos(self): |
| 250 |
return self.get_path_info() |
| 251 |
|
| 252 |
@cached_property |
| 253 |
def cache_name(self): |
| 254 |
""" |
| 255 |
Return the name of the cache key to use for storing an instance of the |
| 256 |
forward model on the reverse model. |
| 257 |
""" |
| 258 |
return self.accessor_name |
| 259 |
|
| 260 |
|
| 261 |
class ManyToOneRel(ForeignObjectRel): |
| 262 |
""" |
| 263 |
Used by the ForeignKey field to store information about the relation. |
| 264 |
|
| 265 |
``_meta.get_fields()`` returns this class to provide access to the field |
| 266 |
flags for the reverse relation. |
| 267 |
|
| 268 |
Note: Because we somewhat abuse the Rel objects by using them as reverse |
| 269 |
fields we get the funny situation where |
| 270 |
``ManyToOneRel.many_to_one == False`` and |
| 271 |
``ManyToOneRel.one_to_many == True``. This is unfortunate but the actual |
| 272 |
ManyToOneRel class is a private API and there is work underway to turn |
| 273 |
reverse relations into actual fields. |
| 274 |
""" |
| 275 |
|
| 276 |
def __init__( |
| 277 |
self, |
| 278 |
field, |
| 279 |
to, |
| 280 |
field_name, |
| 281 |
related_name=None, |
| 282 |
related_query_name=None, |
| 283 |
limit_choices_to=None, |
| 284 |
parent_link=False, |
| 285 |
on_delete=None, |
| 286 |
): |
| 287 |
super().__init__( |
| 288 |
field, |
| 289 |
to, |
| 290 |
related_name=related_name, |
| 291 |
related_query_name=related_query_name, |
| 292 |
limit_choices_to=limit_choices_to, |
| 293 |
parent_link=parent_link, |
| 294 |
on_delete=on_delete, |
| 295 |
) |
| 296 |
|
| 297 |
self.field_name = field_name |
| 298 |
|
| 299 |
def __getstate__(self): |
| 300 |
state = super().__getstate__() |
| 301 |
state.pop("related_model", None) |
| 302 |
return state |
| 303 |
|
| 304 |
@property |
| 305 |
def identity(self): |
| 306 |
return super().identity + (self.field_name,) |
| 307 |
|
| 308 |
def get_related_field(self): |
| 309 |
""" |
| 310 |
Return the Field in the 'to' object to which this relationship is tied. |
| 311 |
""" |
| 312 |
field = self.model._meta.get_field(self.field_name) |
| 313 |
if not field.concrete: |
| 314 |
raise exceptions.FieldDoesNotExist( |
| 315 |
"No related field named '%s'" % self.field_name |
| 316 |
) |
| 317 |
return field |
| 318 |
|
| 319 |
def set_field_name(self): |
| 320 |
self.field_name = self.field_name or self.model._meta.pk.name |
| 321 |
|
| 322 |
|
| 323 |
class OneToOneRel(ManyToOneRel): |
| 324 |
""" |
| 325 |
Used by OneToOneField to store information about the relation. |
| 326 |
|
| 327 |
``_meta.get_fields()`` returns this class to provide access to the field |
| 328 |
flags for the reverse relation. |
| 329 |
""" |
| 330 |
|
| 331 |
def __init__( |
| 332 |
self, |
| 333 |
field, |
| 334 |
to, |
| 335 |
field_name, |
| 336 |
related_name=None, |
| 337 |
related_query_name=None, |
| 338 |
limit_choices_to=None, |
| 339 |
parent_link=False, |
| 340 |
on_delete=None, |
| 341 |
): |
| 342 |
super().__init__( |
| 343 |
field, |
| 344 |
to, |
| 345 |
field_name, |
| 346 |
related_name=related_name, |
| 347 |
related_query_name=related_query_name, |
| 348 |
limit_choices_to=limit_choices_to, |
| 349 |
parent_link=parent_link, |
| 350 |
on_delete=on_delete, |
| 351 |
) |
| 352 |
|
| 353 |
self.multiple = False |
| 354 |
|
| 355 |
|
| 356 |
class ManyToManyRel(ForeignObjectRel): |
| 357 |
""" |
| 358 |
Used by ManyToManyField to store information about the relation. |
| 359 |
|
| 360 |
``_meta.get_fields()`` returns this class to provide access to the field |
| 361 |
flags for the reverse relation. |
| 362 |
""" |
| 363 |
|
| 364 |
def __init__( |
| 365 |
self, |
| 366 |
field, |
| 367 |
to, |
| 368 |
related_name=None, |
| 369 |
related_query_name=None, |
| 370 |
limit_choices_to=None, |
| 371 |
symmetrical=True, |
| 372 |
through=None, |
| 373 |
through_fields=None, |
| 374 |
db_constraint=True, |
| 375 |
): |
| 376 |
super().__init__( |
| 377 |
field, |
| 378 |
to, |
| 379 |
related_name=related_name, |
| 380 |
related_query_name=related_query_name, |
| 381 |
limit_choices_to=limit_choices_to, |
| 382 |
) |
| 383 |
|
| 384 |
if through and not db_constraint: |
| 385 |
raise ValueError("Can't supply a through model and db_constraint=False") |
| 386 |
self.through = through |
| 387 |
|
| 388 |
if through_fields and not through: |
| 389 |
raise ValueError("Cannot specify through_fields without a through model") |
| 390 |
self.through_fields = through_fields |
| 391 |
|
| 392 |
self.symmetrical = symmetrical |
| 393 |
self.db_constraint = db_constraint |
| 394 |
|
| 395 |
@property |
| 396 |
def identity(self): |
| 397 |
return super().identity + ( |
| 398 |
self.through, |
| 399 |
make_hashable(self.through_fields), |
| 400 |
self.db_constraint, |
| 401 |
) |
| 402 |
|
| 403 |
def get_related_field(self): |
| 404 |
""" |
| 405 |
Return the field in the 'to' object to which this relationship is tied. |
| 406 |
Provided for symmetry with ManyToOneRel. |
| 407 |
""" |
| 408 |
opts = self.through._meta |
| 409 |
if self.through_fields: |
| 410 |
field = opts.get_field(self.through_fields[0]) |
| 411 |
else: |
| 412 |
for field in opts.fields: |
| 413 |
rel = getattr(field, "remote_field", None) |
| 414 |
if rel and rel.model == self.model: |
| 415 |
break |
| 416 |
return field.foreign_related_fields[0] |