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.
 
 
 
 

1720 lines
70 KiB

  1. from __future__ import unicode_literals
  2. import copy
  3. import inspect
  4. import warnings
  5. from itertools import chain
  6. from django.apps import apps
  7. from django.conf import settings
  8. from django.core import checks
  9. from django.core.exceptions import (
  10. NON_FIELD_ERRORS, FieldDoesNotExist, FieldError, MultipleObjectsReturned,
  11. ObjectDoesNotExist, ValidationError,
  12. )
  13. from django.db import (
  14. DEFAULT_DB_ALIAS, DJANGO_VERSION_PICKLE_KEY, DatabaseError, connections,
  15. router, transaction,
  16. )
  17. from django.db.models import signals
  18. from django.db.models.constants import LOOKUP_SEP
  19. from django.db.models.deletion import CASCADE, Collector
  20. from django.db.models.fields import AutoField
  21. from django.db.models.fields.related import (
  22. ForeignObjectRel, ManyToOneRel, OneToOneField, lazy_related_operation,
  23. resolve_relation,
  24. )
  25. from django.db.models.manager import ensure_default_manager
  26. from django.db.models.options import Options
  27. from django.db.models.query import Q
  28. from django.db.models.query_utils import (
  29. DeferredAttribute, deferred_class_factory,
  30. )
  31. from django.db.models.utils import make_model_tuple
  32. from django.utils import six
  33. from django.utils.encoding import force_str, force_text
  34. from django.utils.functional import curry
  35. from django.utils.six.moves import zip
  36. from django.utils.text import capfirst, get_text_list
  37. from django.utils.translation import ugettext_lazy as _
  38. from django.utils.version import get_version
  39. def subclass_exception(name, parents, module, attached_to=None):
  40. """
  41. Create exception subclass. Used by ModelBase below.
  42. If 'attached_to' is supplied, the exception will be created in a way that
  43. allows it to be pickled, assuming the returned exception class will be added
  44. as an attribute to the 'attached_to' class.
  45. """
  46. class_dict = {'__module__': module}
  47. if attached_to is not None:
  48. def __reduce__(self):
  49. # Exceptions are special - they've got state that isn't
  50. # in self.__dict__. We assume it is all in self.args.
  51. return (unpickle_inner_exception, (attached_to, name), self.args)
  52. def __setstate__(self, args):
  53. self.args = args
  54. class_dict['__reduce__'] = __reduce__
  55. class_dict['__setstate__'] = __setstate__
  56. return type(name, parents, class_dict)
  57. class ModelBase(type):
  58. """
  59. Metaclass for all models.
  60. """
  61. def __new__(cls, name, bases, attrs):
  62. super_new = super(ModelBase, cls).__new__
  63. # Also ensure initialization is only performed for subclasses of Model
  64. # (excluding Model class itself).
  65. parents = [b for b in bases if isinstance(b, ModelBase)]
  66. if not parents:
  67. return super_new(cls, name, bases, attrs)
  68. # Create the class.
  69. module = attrs.pop('__module__')
  70. new_class = super_new(cls, name, bases, {'__module__': module})
  71. attr_meta = attrs.pop('Meta', None)
  72. abstract = getattr(attr_meta, 'abstract', False)
  73. if not attr_meta:
  74. meta = getattr(new_class, 'Meta', None)
  75. else:
  76. meta = attr_meta
  77. base_meta = getattr(new_class, '_meta', None)
  78. app_label = None
  79. # Look for an application configuration to attach the model to.
  80. app_config = apps.get_containing_app_config(module)
  81. if getattr(meta, 'app_label', None) is None:
  82. if app_config is None:
  83. if not abstract:
  84. raise RuntimeError(
  85. "Model class %s.%s doesn't declare an explicit "
  86. "app_label and isn't in an application in "
  87. "INSTALLED_APPS." % (module, name)
  88. )
  89. else:
  90. app_label = app_config.label
  91. new_class.add_to_class('_meta', Options(meta, app_label))
  92. if not abstract:
  93. new_class.add_to_class(
  94. 'DoesNotExist',
  95. subclass_exception(
  96. str('DoesNotExist'),
  97. tuple(
  98. x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract
  99. ) or (ObjectDoesNotExist,),
  100. module,
  101. attached_to=new_class))
  102. new_class.add_to_class(
  103. 'MultipleObjectsReturned',
  104. subclass_exception(
  105. str('MultipleObjectsReturned'),
  106. tuple(
  107. x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract
  108. ) or (MultipleObjectsReturned,),
  109. module,
  110. attached_to=new_class))
  111. if base_meta and not base_meta.abstract:
  112. # Non-abstract child classes inherit some attributes from their
  113. # non-abstract parent (unless an ABC comes before it in the
  114. # method resolution order).
  115. if not hasattr(meta, 'ordering'):
  116. new_class._meta.ordering = base_meta.ordering
  117. if not hasattr(meta, 'get_latest_by'):
  118. new_class._meta.get_latest_by = base_meta.get_latest_by
  119. is_proxy = new_class._meta.proxy
  120. # If the model is a proxy, ensure that the base class
  121. # hasn't been swapped out.
  122. if is_proxy and base_meta and base_meta.swapped:
  123. raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped))
  124. if getattr(new_class, '_default_manager', None):
  125. if not is_proxy:
  126. # Multi-table inheritance doesn't inherit default manager from
  127. # parents.
  128. new_class._default_manager = None
  129. new_class._base_manager = None
  130. else:
  131. # Proxy classes do inherit parent's default manager, if none is
  132. # set explicitly.
  133. new_class._default_manager = new_class._default_manager._copy_to_model(new_class)
  134. new_class._base_manager = new_class._base_manager._copy_to_model(new_class)
  135. # Add all attributes to the class.
  136. for obj_name, obj in attrs.items():
  137. new_class.add_to_class(obj_name, obj)
  138. # All the fields of any type declared on this model
  139. new_fields = chain(
  140. new_class._meta.local_fields,
  141. new_class._meta.local_many_to_many,
  142. new_class._meta.virtual_fields
  143. )
  144. field_names = {f.name for f in new_fields}
  145. # Basic setup for proxy models.
  146. if is_proxy:
  147. base = None
  148. for parent in [kls for kls in parents if hasattr(kls, '_meta')]:
  149. if parent._meta.abstract:
  150. if parent._meta.fields:
  151. raise TypeError(
  152. "Abstract base class containing model fields not "
  153. "permitted for proxy model '%s'." % name
  154. )
  155. else:
  156. continue
  157. if base is not None:
  158. raise TypeError("Proxy model '%s' has more than one non-abstract model base class." % name)
  159. else:
  160. base = parent
  161. if base is None:
  162. raise TypeError("Proxy model '%s' has no non-abstract model base class." % name)
  163. new_class._meta.setup_proxy(base)
  164. new_class._meta.concrete_model = base._meta.concrete_model
  165. base._meta.concrete_model._meta.proxied_children.append(new_class._meta)
  166. else:
  167. new_class._meta.concrete_model = new_class
  168. # Collect the parent links for multi-table inheritance.
  169. parent_links = {}
  170. for base in reversed([new_class] + parents):
  171. # Conceptually equivalent to `if base is Model`.
  172. if not hasattr(base, '_meta'):
  173. continue
  174. # Skip concrete parent classes.
  175. if base != new_class and not base._meta.abstract:
  176. continue
  177. # Locate OneToOneField instances.
  178. for field in base._meta.local_fields:
  179. if isinstance(field, OneToOneField):
  180. related = resolve_relation(new_class, field.remote_field.model)
  181. parent_links[make_model_tuple(related)] = field
  182. # Do the appropriate setup for any model parents.
  183. for base in parents:
  184. original_base = base
  185. if not hasattr(base, '_meta'):
  186. # Things without _meta aren't functional models, so they're
  187. # uninteresting parents.
  188. continue
  189. parent_fields = base._meta.local_fields + base._meta.local_many_to_many
  190. # Check for clashes between locally declared fields and those
  191. # on the base classes (we cannot handle shadowed fields at the
  192. # moment).
  193. for field in parent_fields:
  194. if field.name in field_names:
  195. raise FieldError(
  196. 'Local field %r in class %r clashes '
  197. 'with field of similar name from '
  198. 'base class %r' % (field.name, name, base.__name__)
  199. )
  200. if not base._meta.abstract:
  201. # Concrete classes...
  202. base = base._meta.concrete_model
  203. base_key = make_model_tuple(base)
  204. if base_key in parent_links:
  205. field = parent_links[base_key]
  206. elif not is_proxy:
  207. attr_name = '%s_ptr' % base._meta.model_name
  208. field = OneToOneField(
  209. base,
  210. on_delete=CASCADE,
  211. name=attr_name,
  212. auto_created=True,
  213. parent_link=True,
  214. )
  215. # Only add the ptr field if it's not already present;
  216. # e.g. migrations will already have it specified
  217. if not hasattr(new_class, attr_name):
  218. new_class.add_to_class(attr_name, field)
  219. else:
  220. field = None
  221. new_class._meta.parents[base] = field
  222. else:
  223. base_parents = base._meta.parents.copy()
  224. # .. and abstract ones.
  225. for field in parent_fields:
  226. new_field = copy.deepcopy(field)
  227. new_class.add_to_class(field.name, new_field)
  228. # Replace parent links defined on this base by the new
  229. # field as it will be appropriately resolved if required.
  230. if field.one_to_one:
  231. for parent, parent_link in base_parents.items():
  232. if field == parent_link:
  233. base_parents[parent] = new_field
  234. # Pass any non-abstract parent classes onto child.
  235. new_class._meta.parents.update(base_parents)
  236. # Inherit managers from the abstract base classes.
  237. new_class.copy_managers(base._meta.abstract_managers)
  238. # Proxy models inherit the non-abstract managers from their base,
  239. # unless they have redefined any of them.
  240. if is_proxy:
  241. new_class.copy_managers(original_base._meta.concrete_managers)
  242. # Inherit virtual fields (like GenericForeignKey) from the parent
  243. # class
  244. for field in base._meta.virtual_fields:
  245. if base._meta.abstract and field.name in field_names:
  246. raise FieldError(
  247. 'Local field %r in class %r clashes '
  248. 'with field of similar name from '
  249. 'abstract base class %r' % (field.name, name, base.__name__)
  250. )
  251. new_class.add_to_class(field.name, copy.deepcopy(field))
  252. if abstract:
  253. # Abstract base models can't be instantiated and don't appear in
  254. # the list of models for an app. We do the final setup for them a
  255. # little differently from normal models.
  256. attr_meta.abstract = False
  257. new_class.Meta = attr_meta
  258. return new_class
  259. new_class._prepare()
  260. new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
  261. return new_class
  262. def copy_managers(cls, base_managers):
  263. # This is in-place sorting of an Options attribute, but that's fine.
  264. base_managers.sort()
  265. for _, mgr_name, manager in base_managers: # NOQA (redefinition of _)
  266. val = getattr(cls, mgr_name, None)
  267. if not val or val is manager:
  268. new_manager = manager._copy_to_model(cls)
  269. cls.add_to_class(mgr_name, new_manager)
  270. def add_to_class(cls, name, value):
  271. # We should call the contribute_to_class method only if it's bound
  272. if not inspect.isclass(value) and hasattr(value, 'contribute_to_class'):
  273. value.contribute_to_class(cls, name)
  274. else:
  275. setattr(cls, name, value)
  276. def _prepare(cls):
  277. """
  278. Creates some methods once self._meta has been populated.
  279. """
  280. opts = cls._meta
  281. opts._prepare(cls)
  282. if opts.order_with_respect_to:
  283. cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True)
  284. cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False)
  285. # Defer creating accessors on the foreign class until it has been
  286. # created and registered. If remote_field is None, we're ordering
  287. # with respect to a GenericForeignKey and don't know what the
  288. # foreign class is - we'll add those accessors later in
  289. # contribute_to_class().
  290. if opts.order_with_respect_to.remote_field:
  291. wrt = opts.order_with_respect_to
  292. remote = wrt.remote_field.model
  293. lazy_related_operation(make_foreign_order_accessors, cls, remote)
  294. # Give the class a docstring -- its definition.
  295. if cls.__doc__ is None:
  296. cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join(f.name for f in opts.fields))
  297. get_absolute_url_override = settings.ABSOLUTE_URL_OVERRIDES.get(opts.label_lower)
  298. if get_absolute_url_override:
  299. setattr(cls, 'get_absolute_url', get_absolute_url_override)
  300. ensure_default_manager(cls)
  301. signals.class_prepared.send(sender=cls)
  302. class ModelState(object):
  303. """
  304. A class for storing instance state
  305. """
  306. def __init__(self, db=None):
  307. self.db = db
  308. # If true, uniqueness validation checks will consider this a new, as-yet-unsaved object.
  309. # Necessary for correct validation of new instances of objects with explicit (non-auto) PKs.
  310. # This impacts validation only; it has no effect on the actual save.
  311. self.adding = True
  312. class Model(six.with_metaclass(ModelBase)):
  313. _deferred = False
  314. def __init__(self, *args, **kwargs):
  315. signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
  316. # Set up the storage for instance state
  317. self._state = ModelState()
  318. # There is a rather weird disparity here; if kwargs, it's set, then args
  319. # overrides it. It should be one or the other; don't duplicate the work
  320. # The reason for the kwargs check is that standard iterator passes in by
  321. # args, and instantiation for iteration is 33% faster.
  322. args_len = len(args)
  323. if args_len > len(self._meta.concrete_fields):
  324. # Daft, but matches old exception sans the err msg.
  325. raise IndexError("Number of args exceeds number of fields")
  326. if not kwargs:
  327. fields_iter = iter(self._meta.concrete_fields)
  328. # The ordering of the zip calls matter - zip throws StopIteration
  329. # when an iter throws it. So if the first iter throws it, the second
  330. # is *not* consumed. We rely on this, so don't change the order
  331. # without changing the logic.
  332. for val, field in zip(args, fields_iter):
  333. setattr(self, field.attname, val)
  334. else:
  335. # Slower, kwargs-ready version.
  336. fields_iter = iter(self._meta.fields)
  337. for val, field in zip(args, fields_iter):
  338. setattr(self, field.attname, val)
  339. kwargs.pop(field.name, None)
  340. # Maintain compatibility with existing calls.
  341. if isinstance(field.remote_field, ManyToOneRel):
  342. kwargs.pop(field.attname, None)
  343. # Now we're left with the unprocessed fields that *must* come from
  344. # keywords, or default.
  345. for field in fields_iter:
  346. is_related_object = False
  347. # This slightly odd construct is so that we can access any
  348. # data-descriptor object (DeferredAttribute) without triggering its
  349. # __get__ method.
  350. if (field.attname not in kwargs and
  351. (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
  352. or field.column is None)):
  353. # This field will be populated on request.
  354. continue
  355. if kwargs:
  356. if isinstance(field.remote_field, ForeignObjectRel):
  357. try:
  358. # Assume object instance was passed in.
  359. rel_obj = kwargs.pop(field.name)
  360. is_related_object = True
  361. except KeyError:
  362. try:
  363. # Object instance wasn't passed in -- must be an ID.
  364. val = kwargs.pop(field.attname)
  365. except KeyError:
  366. val = field.get_default()
  367. else:
  368. # Object instance was passed in. Special case: You can
  369. # pass in "None" for related objects if it's allowed.
  370. if rel_obj is None and field.null:
  371. val = None
  372. else:
  373. try:
  374. val = kwargs.pop(field.attname)
  375. except KeyError:
  376. # This is done with an exception rather than the
  377. # default argument on pop because we don't want
  378. # get_default() to be evaluated, and then not used.
  379. # Refs #12057.
  380. val = field.get_default()
  381. else:
  382. val = field.get_default()
  383. if is_related_object:
  384. # If we are passed a related instance, set it using the
  385. # field.name instead of field.attname (e.g. "user" instead of
  386. # "user_id") so that the object gets properly cached (and type
  387. # checked) by the RelatedObjectDescriptor.
  388. setattr(self, field.name, rel_obj)
  389. else:
  390. setattr(self, field.attname, val)
  391. if kwargs:
  392. for prop in list(kwargs):
  393. try:
  394. if isinstance(getattr(self.__class__, prop), property):
  395. setattr(self, prop, kwargs.pop(prop))
  396. except AttributeError:
  397. pass
  398. if kwargs:
  399. raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
  400. super(Model, self).__init__()
  401. signals.post_init.send(sender=self.__class__, instance=self)
  402. @classmethod
  403. def from_db(cls, db, field_names, values):
  404. if cls._deferred:
  405. new = cls(**dict(zip(field_names, values)))
  406. else:
  407. new = cls(*values)
  408. new._state.adding = False
  409. new._state.db = db
  410. return new
  411. def __repr__(self):
  412. try:
  413. u = six.text_type(self)
  414. except (UnicodeEncodeError, UnicodeDecodeError):
  415. u = '[Bad Unicode data]'
  416. return force_str('<%s: %s>' % (self.__class__.__name__, u))
  417. def __str__(self):
  418. if six.PY2 and hasattr(self, '__unicode__'):
  419. return force_text(self).encode('utf-8')
  420. return str('%s object' % self.__class__.__name__)
  421. def __eq__(self, other):
  422. if not isinstance(other, Model):
  423. return False
  424. if self._meta.concrete_model != other._meta.concrete_model:
  425. return False
  426. my_pk = self._get_pk_val()
  427. if my_pk is None:
  428. return self is other
  429. return my_pk == other._get_pk_val()
  430. def __ne__(self, other):
  431. return not self.__eq__(other)
  432. def __hash__(self):
  433. if self._get_pk_val() is None:
  434. raise TypeError("Model instances without primary key value are unhashable")
  435. return hash(self._get_pk_val())
  436. def __reduce__(self):
  437. """
  438. Provides pickling support. Normally, this just dispatches to Python's
  439. standard handling. However, for models with deferred field loading, we
  440. need to do things manually, as they're dynamically created classes and
  441. only module-level classes can be pickled by the default path.
  442. """
  443. data = self.__dict__
  444. data[DJANGO_VERSION_PICKLE_KEY] = get_version()
  445. if not self._deferred:
  446. class_id = self._meta.app_label, self._meta.object_name
  447. return model_unpickle, (class_id, [], simple_class_factory), data
  448. defers = []
  449. for field in self._meta.fields:
  450. if isinstance(self.__class__.__dict__.get(field.attname),
  451. DeferredAttribute):
  452. defers.append(field.attname)
  453. model = self._meta.proxy_for_model
  454. class_id = model._meta.app_label, model._meta.object_name
  455. return (model_unpickle, (class_id, defers, deferred_class_factory), data)
  456. def __setstate__(self, state):
  457. msg = None
  458. pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)
  459. if pickled_version:
  460. current_version = get_version()
  461. if current_version != pickled_version:
  462. msg = ("Pickled model instance's Django version %s does"
  463. " not match the current version %s."
  464. % (pickled_version, current_version))
  465. else:
  466. msg = "Pickled model instance's Django version is not specified."
  467. if msg:
  468. warnings.warn(msg, RuntimeWarning, stacklevel=2)
  469. self.__dict__.update(state)
  470. def _get_pk_val(self, meta=None):
  471. if not meta:
  472. meta = self._meta
  473. return getattr(self, meta.pk.attname)
  474. def _set_pk_val(self, value):
  475. return setattr(self, self._meta.pk.attname, value)
  476. pk = property(_get_pk_val, _set_pk_val)
  477. def get_deferred_fields(self):
  478. """
  479. Returns a set containing names of deferred fields for this instance.
  480. """
  481. return {
  482. f.attname for f in self._meta.concrete_fields
  483. if isinstance(self.__class__.__dict__.get(f.attname), DeferredAttribute)
  484. }
  485. def refresh_from_db(self, using=None, fields=None, **kwargs):
  486. """
  487. Reloads field values from the database.
  488. By default, the reloading happens from the database this instance was
  489. loaded from, or by the read router if this instance wasn't loaded from
  490. any database. The using parameter will override the default.
  491. Fields can be used to specify which fields to reload. The fields
  492. should be an iterable of field attnames. If fields is None, then
  493. all non-deferred fields are reloaded.
  494. When accessing deferred fields of an instance, the deferred loading
  495. of the field will call this method.
  496. """
  497. if fields is not None:
  498. if len(fields) == 0:
  499. return
  500. if any(LOOKUP_SEP in f for f in fields):
  501. raise ValueError(
  502. 'Found "%s" in fields argument. Relations and transforms '
  503. 'are not allowed in fields.' % LOOKUP_SEP)
  504. db = using if using is not None else self._state.db
  505. if self._deferred:
  506. non_deferred_model = self._meta.proxy_for_model
  507. else:
  508. non_deferred_model = self.__class__
  509. db_instance_qs = non_deferred_model._default_manager.using(db).filter(pk=self.pk)
  510. # Use provided fields, if not set then reload all non-deferred fields.
  511. if fields is not None:
  512. fields = list(fields)
  513. db_instance_qs = db_instance_qs.only(*fields)
  514. elif self._deferred:
  515. deferred_fields = self.get_deferred_fields()
  516. fields = [f.attname for f in self._meta.concrete_fields
  517. if f.attname not in deferred_fields]
  518. db_instance_qs = db_instance_qs.only(*fields)
  519. db_instance = db_instance_qs.get()
  520. non_loaded_fields = db_instance.get_deferred_fields()
  521. for field in self._meta.concrete_fields:
  522. if field.attname in non_loaded_fields:
  523. # This field wasn't refreshed - skip ahead.
  524. continue
  525. setattr(self, field.attname, getattr(db_instance, field.attname))
  526. # Throw away stale foreign key references.
  527. if field.is_relation and field.get_cache_name() in self.__dict__:
  528. rel_instance = getattr(self, field.get_cache_name())
  529. local_val = getattr(db_instance, field.attname)
  530. related_val = None if rel_instance is None else getattr(rel_instance, field.target_field.attname)
  531. if local_val != related_val or (local_val is None and related_val is None):
  532. del self.__dict__[field.get_cache_name()]
  533. self._state.db = db_instance._state.db
  534. def serializable_value(self, field_name):
  535. """
  536. Returns the value of the field name for this instance. If the field is
  537. a foreign key, returns the id value, instead of the object. If there's
  538. no Field object with this name on the model, the model attribute's
  539. value is returned directly.
  540. Used to serialize a field's value (in the serializer, or form output,
  541. for example). Normally, you would just access the attribute directly
  542. and not use this method.
  543. """
  544. try:
  545. field = self._meta.get_field(field_name)
  546. except FieldDoesNotExist:
  547. return getattr(self, field_name)
  548. return getattr(self, field.attname)
  549. def save(self, force_insert=False, force_update=False, using=None,
  550. update_fields=None):
  551. """
  552. Saves the current instance. Override this in a subclass if you want to
  553. control the saving process.
  554. The 'force_insert' and 'force_update' parameters can be used to insist
  555. that the "save" must be an SQL insert or update (or equivalent for
  556. non-SQL backends), respectively. Normally, they should not be set.
  557. """
  558. # Ensure that a model instance without a PK hasn't been assigned to
  559. # a ForeignKey or OneToOneField on this model. If the field is
  560. # nullable, allowing the save() would result in silent data loss.
  561. for field in self._meta.concrete_fields:
  562. if field.is_relation:
  563. # If the related field isn't cached, then an instance hasn't
  564. # been assigned and there's no need to worry about this check.
  565. try:
  566. getattr(self, field.get_cache_name())
  567. except AttributeError:
  568. continue
  569. obj = getattr(self, field.name, None)
  570. # A pk may have been assigned manually to a model instance not
  571. # saved to the database (or auto-generated in a case like
  572. # UUIDField), but we allow the save to proceed and rely on the
  573. # database to raise an IntegrityError if applicable. If
  574. # constraints aren't supported by the database, there's the
  575. # unavoidable risk of data corruption.
  576. if obj and obj.pk is None:
  577. # Remove the object from a related instance cache.
  578. if not field.remote_field.multiple:
  579. delattr(obj, field.remote_field.get_cache_name())
  580. raise ValueError(
  581. "save() prohibited to prevent data loss due to "
  582. "unsaved related object '%s'." % field.name
  583. )
  584. using = using or router.db_for_write(self.__class__, instance=self)
  585. if force_insert and (force_update or update_fields):
  586. raise ValueError("Cannot force both insert and updating in model saving.")
  587. if update_fields is not None:
  588. # If update_fields is empty, skip the save. We do also check for
  589. # no-op saves later on for inheritance cases. This bailout is
  590. # still needed for skipping signal sending.
  591. if len(update_fields) == 0:
  592. return
  593. update_fields = frozenset(update_fields)
  594. field_names = set()
  595. for field in self._meta.fields:
  596. if not field.primary_key:
  597. field_names.add(field.name)
  598. if field.name != field.attname:
  599. field_names.add(field.attname)
  600. non_model_fields = update_fields.difference(field_names)
  601. if non_model_fields:
  602. raise ValueError("The following fields do not exist in this "
  603. "model or are m2m fields: %s"
  604. % ', '.join(non_model_fields))
  605. # If saving to the same database, and this model is deferred, then
  606. # automatically do a "update_fields" save on the loaded fields.
  607. elif not force_insert and self._deferred and using == self._state.db:
  608. field_names = set()
  609. for field in self._meta.concrete_fields:
  610. if not field.primary_key and not hasattr(field, 'through'):
  611. field_names.add(field.attname)
  612. deferred_fields = [
  613. f.attname for f in self._meta.fields
  614. if (f.attname not in self.__dict__ and
  615. isinstance(self.__class__.__dict__[f.attname], DeferredAttribute))
  616. ]
  617. loaded_fields = field_names.difference(deferred_fields)
  618. if loaded_fields:
  619. update_fields = frozenset(loaded_fields)
  620. self.save_base(using=using, force_insert=force_insert,
  621. force_update=force_update, update_fields=update_fields)
  622. save.alters_data = True
  623. def save_base(self, raw=False, force_insert=False,
  624. force_update=False, using=None, update_fields=None):
  625. """
  626. Handles the parts of saving which should be done only once per save,
  627. yet need to be done in raw saves, too. This includes some sanity
  628. checks and signal sending.
  629. The 'raw' argument is telling save_base not to save any parent
  630. models and not to do any changes to the values before save. This
  631. is used by fixture loading.
  632. """
  633. using = using or router.db_for_write(self.__class__, instance=self)
  634. assert not (force_insert and (force_update or update_fields))
  635. assert update_fields is None or len(update_fields) > 0
  636. cls = origin = self.__class__
  637. # Skip proxies, but keep the origin as the proxy model.
  638. if cls._meta.proxy:
  639. cls = cls._meta.concrete_model
  640. meta = cls._meta
  641. if not meta.auto_created:
  642. signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
  643. update_fields=update_fields)
  644. with transaction.atomic(using=using, savepoint=False):
  645. if not raw:
  646. self._save_parents(cls, using, update_fields)
  647. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  648. # Store the database on which the object was saved
  649. self._state.db = using
  650. # Once saved, this is no longer a to-be-added instance.
  651. self._state.adding = False
  652. # Signal that the save is complete
  653. if not meta.auto_created:
  654. signals.post_save.send(sender=origin, instance=self, created=(not updated),
  655. update_fields=update_fields, raw=raw, using=using)
  656. save_base.alters_data = True
  657. def _save_parents(self, cls, using, update_fields):
  658. """
  659. Saves all the parents of cls using values from self.
  660. """
  661. meta = cls._meta
  662. for parent, field in meta.parents.items():
  663. # Make sure the link fields are synced between parent and self.
  664. if (field and getattr(self, parent._meta.pk.attname) is None
  665. and getattr(self, field.attname) is not None):
  666. setattr(self, parent._meta.pk.attname, getattr(self, field.attname))
  667. self._save_parents(cls=parent, using=using, update_fields=update_fields)
  668. self._save_table(cls=parent, using=using, update_fields=update_fields)
  669. # Set the parent's PK value to self.
  670. if field:
  671. setattr(self, field.attname, self._get_pk_val(parent._meta))
  672. # Since we didn't have an instance of the parent handy set
  673. # attname directly, bypassing the descriptor. Invalidate
  674. # the related object cache, in case it's been accidentally
  675. # populated. A fresh instance will be re-built from the
  676. # database if necessary.
  677. cache_name = field.get_cache_name()
  678. if hasattr(self, cache_name):
  679. delattr(self, cache_name)
  680. def _save_table(self, raw=False, cls=None, force_insert=False,
  681. force_update=False, using=None, update_fields=None):
  682. """
  683. Does the heavy-lifting involved in saving. Updates or inserts the data
  684. for a single table.
  685. """
  686. meta = cls._meta
  687. non_pks = [f for f in meta.local_concrete_fields if not f.primary_key]
  688. if update_fields:
  689. non_pks = [f for f in non_pks
  690. if f.name in update_fields or f.attname in update_fields]
  691. pk_val = self._get_pk_val(meta)
  692. if pk_val is None:
  693. pk_val = meta.pk.get_pk_value_on_save(self)
  694. setattr(self, meta.pk.attname, pk_val)
  695. pk_set = pk_val is not None
  696. if not pk_set and (force_update or update_fields):
  697. raise ValueError("Cannot force an update in save() with no primary key.")
  698. updated = False
  699. # If possible, try an UPDATE. If that doesn't update anything, do an INSERT.
  700. if pk_set and not force_insert:
  701. base_qs = cls._base_manager.using(using)
  702. values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
  703. for f in non_pks]
  704. forced_update = update_fields or force_update
  705. updated = self._do_update(base_qs, using, pk_val, values, update_fields,
  706. forced_update)
  707. if force_update and not updated:
  708. raise DatabaseError("Forced update did not affect any rows.")
  709. if update_fields and not updated:
  710. raise DatabaseError("Save with update_fields did not affect any rows.")
  711. if not updated:
  712. if meta.order_with_respect_to:
  713. # If this is a model with an order_with_respect_to
  714. # autopopulate the _order field
  715. field = meta.order_with_respect_to
  716. filter_args = field.get_filter_kwargs_for_object(self)
  717. order_value = cls._base_manager.using(using).filter(**filter_args).count()
  718. self._order = order_value
  719. fields = meta.local_concrete_fields
  720. if not pk_set:
  721. fields = [f for f in fields if not isinstance(f, AutoField)]
  722. update_pk = bool(meta.has_auto_field and not pk_set)
  723. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  724. if update_pk:
  725. setattr(self, meta.pk.attname, result)
  726. return updated
  727. def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update):
  728. """
  729. This method will try to update the model. If the model was updated (in
  730. the sense that an update query was done and a matching row was found
  731. from the DB) the method will return True.
  732. """
  733. filtered = base_qs.filter(pk=pk_val)
  734. if not values:
  735. # We can end up here when saving a model in inheritance chain where
  736. # update_fields doesn't target any field in current model. In that
  737. # case we just say the update succeeded. Another case ending up here
  738. # is a model with just PK - in that case check that the PK still
  739. # exists.
  740. return update_fields is not None or filtered.exists()
  741. if self._meta.select_on_save and not forced_update:
  742. if filtered.exists():
  743. # It may happen that the object is deleted from the DB right after
  744. # this check, causing the subsequent UPDATE to return zero matching
  745. # rows. The same result can occur in some rare cases when the
  746. # database returns zero despite the UPDATE being executed
  747. # successfully (a row is matched and updated). In order to
  748. # distinguish these two cases, the object's existence in the
  749. # database is again checked for if the UPDATE query returns 0.
  750. return filtered._update(values) > 0 or filtered.exists()
  751. else:
  752. return False
  753. return filtered._update(values) > 0
  754. def _do_insert(self, manager, using, fields, update_pk, raw):
  755. """
  756. Do an INSERT. If update_pk is defined then this method should return
  757. the new pk for the model.
  758. """
  759. return manager._insert([self], fields=fields, return_id=update_pk,
  760. using=using, raw=raw)
  761. def delete(self, using=None, keep_parents=False):
  762. using = using or router.db_for_write(self.__class__, instance=self)
  763. assert self._get_pk_val() is not None, (
  764. "%s object can't be deleted because its %s attribute is set to None." %
  765. (self._meta.object_name, self._meta.pk.attname)
  766. )
  767. collector = Collector(using=using)
  768. collector.collect([self], keep_parents=keep_parents)
  769. return collector.delete()
  770. delete.alters_data = True
  771. def _get_FIELD_display(self, field):
  772. value = getattr(self, field.attname)
  773. return force_text(dict(field.flatchoices).get(value, value), strings_only=True)
  774. def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs):
  775. if not self.pk:
  776. raise ValueError("get_next/get_previous cannot be used on unsaved objects.")
  777. op = 'gt' if is_next else 'lt'
  778. order = '' if is_next else '-'
  779. param = force_text(getattr(self, field.attname))
  780. q = Q(**{'%s__%s' % (field.name, op): param})
  781. q = q | Q(**{field.name: param, 'pk__%s' % op: self.pk})
  782. qs = self.__class__._default_manager.using(self._state.db).filter(**kwargs).filter(q).order_by(
  783. '%s%s' % (order, field.name), '%spk' % order
  784. )
  785. try:
  786. return qs[0]
  787. except IndexError:
  788. raise self.DoesNotExist("%s matching query does not exist." % self.__class__._meta.object_name)
  789. def _get_next_or_previous_in_order(self, is_next):
  790. cachename = "__%s_order_cache" % is_next
  791. if not hasattr(self, cachename):
  792. op = 'gt' if is_next else 'lt'
  793. order = '_order' if is_next else '-_order'
  794. order_field = self._meta.order_with_respect_to
  795. filter_args = order_field.get_filter_kwargs_for_object(self)
  796. obj = self._default_manager.filter(**filter_args).filter(**{
  797. '_order__%s' % op: self._default_manager.values('_order').filter(**{
  798. self._meta.pk.name: self.pk
  799. })
  800. }).order_by(order)[:1].get()
  801. setattr(self, cachename, obj)
  802. return getattr(self, cachename)
  803. def prepare_database_save(self, field):
  804. if self.pk is None:
  805. raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
  806. return getattr(self, field.remote_field.get_related_field().attname)
  807. def clean(self):
  808. """
  809. Hook for doing any extra model-wide validation after clean() has been
  810. called on every field by self.clean_fields. Any ValidationError raised
  811. by this method will not be associated with a particular field; it will
  812. have a special-case association with the field defined by NON_FIELD_ERRORS.
  813. """
  814. pass
  815. def validate_unique(self, exclude=None):
  816. """
  817. Checks unique constraints on the model and raises ``ValidationError``
  818. if any failed.
  819. """
  820. unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
  821. errors = self._perform_unique_checks(unique_checks)
  822. date_errors = self._perform_date_checks(date_checks)
  823. for k, v in date_errors.items():
  824. errors.setdefault(k, []).extend(v)
  825. if errors:
  826. raise ValidationError(errors)
  827. def _get_unique_checks(self, exclude=None):
  828. """
  829. Gather a list of checks to perform. Since validate_unique could be
  830. called from a ModelForm, some fields may have been excluded; we can't
  831. perform a unique check on a model that is missing fields involved
  832. in that check.
  833. Fields that did not validate should also be excluded, but they need
  834. to be passed in via the exclude argument.
  835. """
  836. if exclude is None:
  837. exclude = []
  838. unique_checks = []
  839. unique_togethers = [(self.__class__, self._meta.unique_together)]
  840. for parent_class in self._meta.get_parent_list():
  841. if parent_class._meta.unique_together:
  842. unique_togethers.append((parent_class, parent_class._meta.unique_together))
  843. for model_class, unique_together in unique_togethers:
  844. for check in unique_together:
  845. for name in check:
  846. # If this is an excluded field, don't add this check.
  847. if name in exclude:
  848. break
  849. else:
  850. unique_checks.append((model_class, tuple(check)))
  851. # These are checks for the unique_for_<date/year/month>.
  852. date_checks = []
  853. # Gather a list of checks for fields declared as unique and add them to
  854. # the list of checks.
  855. fields_with_class = [(self.__class__, self._meta.local_fields)]
  856. for parent_class in self._meta.get_parent_list():
  857. fields_with_class.append((parent_class, parent_class._meta.local_fields))
  858. for model_class, fields in fields_with_class:
  859. for f in fields:
  860. name = f.name
  861. if name in exclude:
  862. continue
  863. if f.unique:
  864. unique_checks.append((model_class, (name,)))
  865. if f.unique_for_date and f.unique_for_date not in exclude:
  866. date_checks.append((model_class, 'date', name, f.unique_for_date))
  867. if f.unique_for_year and f.unique_for_year not in exclude:
  868. date_checks.append((model_class, 'year', name, f.unique_for_year))
  869. if f.unique_for_month and f.unique_for_month not in exclude:
  870. date_checks.append((model_class, 'month', name, f.unique_for_month))
  871. return unique_checks, date_checks
  872. def _perform_unique_checks(self, unique_checks):
  873. errors = {}
  874. for model_class, unique_check in unique_checks:
  875. # Try to look up an existing object with the same values as this
  876. # object's values for all the unique field.
  877. lookup_kwargs = {}
  878. for field_name in unique_check:
  879. f = self._meta.get_field(field_name)
  880. lookup_value = getattr(self, f.attname)
  881. if lookup_value is None:
  882. # no value, skip the lookup
  883. continue
  884. if f.primary_key and not self._state.adding:
  885. # no need to check for unique primary key when editing
  886. continue
  887. lookup_kwargs[str(field_name)] = lookup_value
  888. # some fields were skipped, no reason to do the check
  889. if len(unique_check) != len(lookup_kwargs):
  890. continue
  891. qs = model_class._default_manager.filter(**lookup_kwargs)
  892. # Exclude the current object from the query if we are editing an
  893. # instance (as opposed to creating a new one)
  894. # Note that we need to use the pk as defined by model_class, not
  895. # self.pk. These can be different fields because model inheritance
  896. # allows single model to have effectively multiple primary keys.
  897. # Refs #17615.
  898. model_class_pk = self._get_pk_val(model_class._meta)
  899. if not self._state.adding and model_class_pk is not None:
  900. qs = qs.exclude(pk=model_class_pk)
  901. if qs.exists():
  902. if len(unique_check) == 1:
  903. key = unique_check[0]
  904. else:
  905. key = NON_FIELD_ERRORS
  906. errors.setdefault(key, []).append(self.unique_error_message(model_class, unique_check))
  907. return errors
  908. def _perform_date_checks(self, date_checks):
  909. errors = {}
  910. for model_class, lookup_type, field, unique_for in date_checks:
  911. lookup_kwargs = {}
  912. # there's a ticket to add a date lookup, we can remove this special
  913. # case if that makes it's way in
  914. date = getattr(self, unique_for)
  915. if date is None:
  916. continue
  917. if lookup_type == 'date':
  918. lookup_kwargs['%s__day' % unique_for] = date.day
  919. lookup_kwargs['%s__month' % unique_for] = date.month
  920. lookup_kwargs['%s__year' % unique_for] = date.year
  921. else:
  922. lookup_kwargs['%s__%s' % (unique_for, lookup_type)] = getattr(date, lookup_type)
  923. lookup_kwargs[field] = getattr(self, field)
  924. qs = model_class._default_manager.filter(**lookup_kwargs)
  925. # Exclude the current object from the query if we are editing an
  926. # instance (as opposed to creating a new one)
  927. if not self._state.adding and self.pk is not None:
  928. qs = qs.exclude(pk=self.pk)
  929. if qs.exists():
  930. errors.setdefault(field, []).append(
  931. self.date_error_message(lookup_type, field, unique_for)
  932. )
  933. return errors
  934. def date_error_message(self, lookup_type, field_name, unique_for):
  935. opts = self._meta
  936. field = opts.get_field(field_name)
  937. return ValidationError(
  938. message=field.error_messages['unique_for_date'],
  939. code='unique_for_date',
  940. params={
  941. 'model': self,
  942. 'model_name': six.text_type(capfirst(opts.verbose_name)),
  943. 'lookup_type': lookup_type,
  944. 'field': field_name,
  945. 'field_label': six.text_type(capfirst(field.verbose_name)),
  946. 'date_field': unique_for,
  947. 'date_field_label': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
  948. }
  949. )
  950. def unique_error_message(self, model_class, unique_check):
  951. opts = model_class._meta
  952. params = {
  953. 'model': self,
  954. 'model_class': model_class,
  955. 'model_name': six.text_type(capfirst(opts.verbose_name)),
  956. 'unique_check': unique_check,
  957. }
  958. # A unique field
  959. if len(unique_check) == 1:
  960. field = opts.get_field(unique_check[0])
  961. params['field_label'] = six.text_type(capfirst(field.verbose_name))
  962. return ValidationError(
  963. message=field.error_messages['unique'],
  964. code='unique',
  965. params=params,
  966. )
  967. # unique_together
  968. else:
  969. field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
  970. params['field_labels'] = six.text_type(get_text_list(field_labels, _('and')))
  971. return ValidationError(
  972. message=_("%(model_name)s with this %(field_labels)s already exists."),
  973. code='unique_together',
  974. params=params,
  975. )
  976. def full_clean(self, exclude=None, validate_unique=True):
  977. """
  978. Calls clean_fields, clean, and validate_unique, on the model,
  979. and raises a ``ValidationError`` for any errors that occurred.
  980. """
  981. errors = {}
  982. if exclude is None:
  983. exclude = []
  984. else:
  985. exclude = list(exclude)
  986. try:
  987. self.clean_fields(exclude=exclude)
  988. except ValidationError as e:
  989. errors = e.update_error_dict(errors)
  990. # Form.clean() is run even if other validation fails, so do the
  991. # same with Model.clean() for consistency.
  992. try:
  993. self.clean()
  994. except ValidationError as e:
  995. errors = e.update_error_dict(errors)
  996. # Run unique checks, but only for fields that passed validation.
  997. if validate_unique:
  998. for name in errors.keys():
  999. if name != NON_FIELD_ERRORS and name not in exclude:
  1000. exclude.append(name)
  1001. try:
  1002. self.validate_unique(exclude=exclude)
  1003. except ValidationError as e:
  1004. errors = e.update_error_dict(errors)
  1005. if errors:
  1006. raise ValidationError(errors)
  1007. def clean_fields(self, exclude=None):
  1008. """
  1009. Cleans all fields and raises a ValidationError containing a dict
  1010. of all validation errors if any occur.
  1011. """
  1012. if exclude is None:
  1013. exclude = []
  1014. errors = {}
  1015. for f in self._meta.fields:
  1016. if f.name in exclude:
  1017. continue
  1018. # Skip validation for empty fields with blank=True. The developer
  1019. # is responsible for making sure they have a valid value.
  1020. raw_value = getattr(self, f.attname)
  1021. if f.blank and raw_value in f.empty_values:
  1022. continue
  1023. try:
  1024. setattr(self, f.attname, f.clean(raw_value, self))
  1025. except ValidationError as e:
  1026. errors[f.name] = e.error_list
  1027. if errors:
  1028. raise ValidationError(errors)
  1029. @classmethod
  1030. def check(cls, **kwargs):
  1031. errors = []
  1032. errors.extend(cls._check_swappable())
  1033. errors.extend(cls._check_model())
  1034. errors.extend(cls._check_managers(**kwargs))
  1035. if not cls._meta.swapped:
  1036. errors.extend(cls._check_fields(**kwargs))
  1037. errors.extend(cls._check_m2m_through_same_relationship())
  1038. errors.extend(cls._check_long_column_names())
  1039. clash_errors = cls._check_id_field() + cls._check_field_name_clashes()
  1040. errors.extend(clash_errors)
  1041. # If there are field name clashes, hide consequent column name
  1042. # clashes.
  1043. if not clash_errors:
  1044. errors.extend(cls._check_column_name_clashes())
  1045. errors.extend(cls._check_index_together())
  1046. errors.extend(cls._check_unique_together())
  1047. errors.extend(cls._check_ordering())
  1048. return errors
  1049. @classmethod
  1050. def _check_swappable(cls):
  1051. """ Check if the swapped model exists. """
  1052. errors = []
  1053. if cls._meta.swapped:
  1054. try:
  1055. apps.get_model(cls._meta.swapped)
  1056. except ValueError:
  1057. errors.append(
  1058. checks.Error(
  1059. "'%s' is not of the form 'app_label.app_name'." % cls._meta.swappable,
  1060. hint=None,
  1061. obj=None,
  1062. id='models.E001',
  1063. )
  1064. )
  1065. except LookupError:
  1066. app_label, model_name = cls._meta.swapped.split('.')
  1067. errors.append(
  1068. checks.Error(
  1069. "'%s' references '%s.%s', which has not been "
  1070. "installed, or is abstract." % (
  1071. cls._meta.swappable, app_label, model_name
  1072. ),
  1073. hint=None,
  1074. obj=None,
  1075. id='models.E002',
  1076. )
  1077. )
  1078. return errors
  1079. @classmethod
  1080. def _check_model(cls):
  1081. errors = []
  1082. if cls._meta.proxy:
  1083. if cls._meta.local_fields or cls._meta.local_many_to_many:
  1084. errors.append(
  1085. checks.Error(
  1086. "Proxy model '%s' contains model fields." % cls.__name__,
  1087. hint=None,
  1088. obj=None,
  1089. id='models.E017',
  1090. )
  1091. )
  1092. return errors
  1093. @classmethod
  1094. def _check_managers(cls, **kwargs):
  1095. """ Perform all manager checks. """
  1096. errors = []
  1097. for __, manager, __ in cls._meta.managers:
  1098. errors.extend(manager.check(**kwargs))
  1099. return errors
  1100. @classmethod
  1101. def _check_fields(cls, **kwargs):
  1102. """ Perform all field checks. """
  1103. errors = []
  1104. for field in cls._meta.local_fields:
  1105. errors.extend(field.check(**kwargs))
  1106. for field in cls._meta.local_many_to_many:
  1107. errors.extend(field.check(from_model=cls, **kwargs))
  1108. return errors
  1109. @classmethod
  1110. def _check_m2m_through_same_relationship(cls):
  1111. """ Check if no relationship model is used by more than one m2m field.
  1112. """
  1113. errors = []
  1114. seen_intermediary_signatures = []
  1115. fields = cls._meta.local_many_to_many
  1116. # Skip when the target model wasn't found.
  1117. fields = (f for f in fields if isinstance(f.remote_field.model, ModelBase))
  1118. # Skip when the relationship model wasn't found.
  1119. fields = (f for f in fields if isinstance(f.remote_field.through, ModelBase))
  1120. for f in fields:
  1121. signature = (f.remote_field.model, cls, f.remote_field.through)
  1122. if signature in seen_intermediary_signatures:
  1123. errors.append(
  1124. checks.Error(
  1125. "The model has two many-to-many relations through "
  1126. "the intermediate model '%s'." % f.remote_field.through._meta.label,
  1127. hint=None,
  1128. obj=cls,
  1129. id='models.E003',
  1130. )
  1131. )
  1132. else:
  1133. seen_intermediary_signatures.append(signature)
  1134. return errors
  1135. @classmethod
  1136. def _check_id_field(cls):
  1137. """ Check if `id` field is a primary key. """
  1138. fields = list(f for f in cls._meta.local_fields
  1139. if f.name == 'id' and f != cls._meta.pk)
  1140. # fields is empty or consists of the invalid "id" field
  1141. if fields and not fields[0].primary_key and cls._meta.pk.name == 'id':
  1142. return [
  1143. checks.Error(
  1144. "'id' can only be used as a field name if the field also "
  1145. "sets 'primary_key=True'.",
  1146. hint=None,
  1147. obj=cls,
  1148. id='models.E004',
  1149. )
  1150. ]
  1151. else:
  1152. return []
  1153. @classmethod
  1154. def _check_field_name_clashes(cls):
  1155. """ Ref #17673. """
  1156. errors = []
  1157. used_fields = {} # name or attname -> field
  1158. # Check that multi-inheritance doesn't cause field name shadowing.
  1159. for parent in cls._meta.get_parent_list():
  1160. for f in parent._meta.local_fields:
  1161. clash = used_fields.get(f.name) or used_fields.get(f.attname) or None
  1162. if clash:
  1163. errors.append(
  1164. checks.Error(
  1165. "The field '%s' from parent model "
  1166. "'%s' clashes with the field '%s' "
  1167. "from parent model '%s'." % (
  1168. clash.name, clash.model._meta,
  1169. f.name, f.model._meta
  1170. ),
  1171. hint=None,
  1172. obj=cls,
  1173. id='models.E005',
  1174. )
  1175. )
  1176. used_fields[f.name] = f
  1177. used_fields[f.attname] = f
  1178. # Check that fields defined in the model don't clash with fields from
  1179. # parents, including auto-generated fields like multi-table inheritance
  1180. # child accessors.
  1181. for parent in cls._meta.get_parent_list():
  1182. for f in parent._meta.get_fields():
  1183. if f not in used_fields:
  1184. used_fields[f.name] = f
  1185. for f in cls._meta.local_fields:
  1186. clash = used_fields.get(f.name) or used_fields.get(f.attname) or None
  1187. # Note that we may detect clash between user-defined non-unique
  1188. # field "id" and automatically added unique field "id", both
  1189. # defined at the same model. This special case is considered in
  1190. # _check_id_field and here we ignore it.
  1191. id_conflict = (f.name == "id" and
  1192. clash and clash.name == "id" and clash.model == cls)
  1193. if clash and not id_conflict:
  1194. errors.append(
  1195. checks.Error(
  1196. "The field '%s' clashes with the field '%s' "
  1197. "from model '%s'." % (
  1198. f.name, clash.name, clash.model._meta
  1199. ),
  1200. hint=None,
  1201. obj=f,
  1202. id='models.E006',
  1203. )
  1204. )
  1205. used_fields[f.name] = f
  1206. used_fields[f.attname] = f
  1207. return errors
  1208. @classmethod
  1209. def _check_column_name_clashes(cls):
  1210. # Store a list of column names which have already been used by other fields.
  1211. used_column_names = []
  1212. errors = []
  1213. for f in cls._meta.local_fields:
  1214. _, column_name = f.get_attname_column()
  1215. # Ensure the column name is not already in use.
  1216. if column_name and column_name in used_column_names:
  1217. errors.append(
  1218. checks.Error(
  1219. "Field '%s' has column name '%s' that is used by "
  1220. "another field." % (f.name, column_name),
  1221. hint="Specify a 'db_column' for the field.",
  1222. obj=cls,
  1223. id='models.E007'
  1224. )
  1225. )
  1226. else:
  1227. used_column_names.append(column_name)
  1228. return errors
  1229. @classmethod
  1230. def _check_index_together(cls):
  1231. """ Check the value of "index_together" option. """
  1232. if not isinstance(cls._meta.index_together, (tuple, list)):
  1233. return [
  1234. checks.Error(
  1235. "'index_together' must be a list or tuple.",
  1236. hint=None,
  1237. obj=cls,
  1238. id='models.E008',
  1239. )
  1240. ]
  1241. elif any(not isinstance(fields, (tuple, list))
  1242. for fields in cls._meta.index_together):
  1243. return [
  1244. checks.Error(
  1245. "All 'index_together' elements must be lists or tuples.",
  1246. hint=None,
  1247. obj=cls,
  1248. id='models.E009',
  1249. )
  1250. ]
  1251. else:
  1252. errors = []
  1253. for fields in cls._meta.index_together:
  1254. errors.extend(cls._check_local_fields(fields, "index_together"))
  1255. return errors
  1256. @classmethod
  1257. def _check_unique_together(cls):
  1258. """ Check the value of "unique_together" option. """
  1259. if not isinstance(cls._meta.unique_together, (tuple, list)):
  1260. return [
  1261. checks.Error(
  1262. "'unique_together' must be a list or tuple.",
  1263. hint=None,
  1264. obj=cls,
  1265. id='models.E010',
  1266. )
  1267. ]
  1268. elif any(not isinstance(fields, (tuple, list))
  1269. for fields in cls._meta.unique_together):
  1270. return [
  1271. checks.Error(
  1272. "All 'unique_together' elements must be lists or tuples.",
  1273. hint=None,
  1274. obj=cls,
  1275. id='models.E011',
  1276. )
  1277. ]
  1278. else:
  1279. errors = []
  1280. for fields in cls._meta.unique_together:
  1281. errors.extend(cls._check_local_fields(fields, "unique_together"))
  1282. return errors
  1283. @classmethod
  1284. def _check_local_fields(cls, fields, option):
  1285. from django.db import models
  1286. # In order to avoid hitting the relation tree prematurely, we use our
  1287. # own fields_map instead of using get_field()
  1288. forward_fields_map = {
  1289. field.name: field for field in cls._meta._get_fields(reverse=False)
  1290. }
  1291. errors = []
  1292. for field_name in fields:
  1293. try:
  1294. field = forward_fields_map[field_name]
  1295. except KeyError:
  1296. errors.append(
  1297. checks.Error(
  1298. "'%s' refers to the non-existent field '%s'." % (
  1299. option, field_name,
  1300. ),
  1301. hint=None,
  1302. obj=cls,
  1303. id='models.E012',
  1304. )
  1305. )
  1306. else:
  1307. if isinstance(field.remote_field, models.ManyToManyRel):
  1308. errors.append(
  1309. checks.Error(
  1310. "'%s' refers to a ManyToManyField '%s', but "
  1311. "ManyToManyFields are not permitted in '%s'." % (
  1312. option, field_name, option,
  1313. ),
  1314. hint=None,
  1315. obj=cls,
  1316. id='models.E013',
  1317. )
  1318. )
  1319. elif field not in cls._meta.local_fields:
  1320. errors.append(
  1321. checks.Error(
  1322. ("'%s' refers to field '%s' which is not local "
  1323. "to model '%s'.") % (
  1324. option, field_name, cls._meta.object_name,
  1325. ),
  1326. hint=("This issue may be caused by multi-table "
  1327. "inheritance."),
  1328. obj=cls,
  1329. id='models.E016',
  1330. )
  1331. )
  1332. return errors
  1333. @classmethod
  1334. def _check_ordering(cls):
  1335. """ Check "ordering" option -- is it a list of strings and do all fields
  1336. exist? """
  1337. if cls._meta._ordering_clash:
  1338. return [
  1339. checks.Error(
  1340. "'ordering' and 'order_with_respect_to' cannot be used together.",
  1341. hint=None,
  1342. obj=cls,
  1343. id='models.E021',
  1344. ),
  1345. ]
  1346. if cls._meta.order_with_respect_to or not cls._meta.ordering:
  1347. return []
  1348. if not isinstance(cls._meta.ordering, (list, tuple)):
  1349. return [
  1350. checks.Error(
  1351. ("'ordering' must be a tuple or list "
  1352. "(even if you want to order by only one field)."),
  1353. hint=None,
  1354. obj=cls,
  1355. id='models.E014',
  1356. )
  1357. ]
  1358. errors = []
  1359. fields = cls._meta.ordering
  1360. # Skip '?' fields.
  1361. fields = (f for f in fields if f != '?')
  1362. # Convert "-field" to "field".
  1363. fields = ((f[1:] if f.startswith('-') else f) for f in fields)
  1364. # Skip ordering in the format field1__field2 (FIXME: checking
  1365. # this format would be nice, but it's a little fiddly).
  1366. fields = (f for f in fields if '__' not in f)
  1367. # Skip ordering on pk. This is always a valid order_by field
  1368. # but is an alias and therefore won't be found by opts.get_field.
  1369. fields = {f for f in fields if f != 'pk'}
  1370. # Check for invalid or non-existent fields in ordering.
  1371. invalid_fields = []
  1372. # Any field name that is not present in field_names does not exist.
  1373. # Also, ordering by m2m fields is not allowed.
  1374. opts = cls._meta
  1375. valid_fields = set(chain.from_iterable(
  1376. (f.name, f.attname) if not (f.auto_created and not f.concrete) else (f.field.related_query_name(),)
  1377. for f in chain(opts.fields, opts.related_objects)
  1378. ))
  1379. invalid_fields.extend(fields - valid_fields)
  1380. for invalid_field in invalid_fields:
  1381. errors.append(
  1382. checks.Error(
  1383. "'ordering' refers to the non-existent field '%s'." % invalid_field,
  1384. hint=None,
  1385. obj=cls,
  1386. id='models.E015',
  1387. )
  1388. )
  1389. return errors
  1390. @classmethod
  1391. def _check_long_column_names(cls):
  1392. """
  1393. Check that any auto-generated column names are shorter than the limits
  1394. for each database in which the model will be created.
  1395. """
  1396. errors = []
  1397. allowed_len = None
  1398. db_alias = None
  1399. # Find the minimum max allowed length among all specified db_aliases.
  1400. for db in settings.DATABASES.keys():
  1401. # skip databases where the model won't be created
  1402. if not router.allow_migrate_model(db, cls):
  1403. continue
  1404. connection = connections[db]
  1405. max_name_length = connection.ops.max_name_length()
  1406. if max_name_length is None or connection.features.truncates_names:
  1407. continue
  1408. else:
  1409. if allowed_len is None:
  1410. allowed_len = max_name_length
  1411. db_alias = db
  1412. elif max_name_length < allowed_len:
  1413. allowed_len = max_name_length
  1414. db_alias = db
  1415. if allowed_len is None:
  1416. return errors
  1417. for f in cls._meta.local_fields:
  1418. _, column_name = f.get_attname_column()
  1419. # Check if auto-generated name for the field is too long
  1420. # for the database.
  1421. if (f.db_column is None and column_name is not None
  1422. and len(column_name) > allowed_len):
  1423. errors.append(
  1424. checks.Error(
  1425. 'Autogenerated column name too long for field "%s". '
  1426. 'Maximum length is "%s" for database "%s".'
  1427. % (column_name, allowed_len, db_alias),
  1428. hint="Set the column name manually using 'db_column'.",
  1429. obj=cls,
  1430. id='models.E018',
  1431. )
  1432. )
  1433. for f in cls._meta.local_many_to_many:
  1434. # Check if auto-generated name for the M2M field is too long
  1435. # for the database.
  1436. for m2m in f.remote_field.through._meta.local_fields:
  1437. _, rel_name = m2m.get_attname_column()
  1438. if (m2m.db_column is None and rel_name is not None
  1439. and len(rel_name) > allowed_len):
  1440. errors.append(
  1441. checks.Error(
  1442. 'Autogenerated column name too long for M2M field '
  1443. '"%s". Maximum length is "%s" for database "%s".'
  1444. % (rel_name, allowed_len, db_alias),
  1445. hint=("Use 'through' to create a separate model "
  1446. "for M2M and then set column_name using "
  1447. "'db_column'."),
  1448. obj=cls,
  1449. id='models.E019',
  1450. )
  1451. )
  1452. return errors
  1453. ############################################
  1454. # HELPER FUNCTIONS (CURRIED MODEL METHODS) #
  1455. ############################################
  1456. # ORDERING METHODS #########################
  1457. def method_set_order(ordered_obj, self, id_list, using=None):
  1458. if using is None:
  1459. using = DEFAULT_DB_ALIAS
  1460. order_wrt = ordered_obj._meta.order_with_respect_to
  1461. filter_args = order_wrt.get_forward_related_filter(self)
  1462. # FIXME: It would be nice if there was an "update many" version of update
  1463. # for situations like this.
  1464. with transaction.atomic(using=using, savepoint=False):
  1465. for i, j in enumerate(id_list):
  1466. ordered_obj.objects.filter(pk=j, **filter_args).update(_order=i)
  1467. def method_get_order(ordered_obj, self):
  1468. order_wrt = ordered_obj._meta.order_with_respect_to
  1469. filter_args = order_wrt.get_forward_related_filter(self)
  1470. pk_name = ordered_obj._meta.pk.name
  1471. return ordered_obj.objects.filter(**filter_args).values_list(pk_name, flat=True)
  1472. def make_foreign_order_accessors(model, related_model):
  1473. setattr(
  1474. related_model,
  1475. 'get_%s_order' % model.__name__.lower(),
  1476. curry(method_get_order, model)
  1477. )
  1478. setattr(
  1479. related_model,
  1480. 'set_%s_order' % model.__name__.lower(),
  1481. curry(method_set_order, model)
  1482. )
  1483. ########
  1484. # MISC #
  1485. ########
  1486. def simple_class_factory(model, attrs):
  1487. """
  1488. Needed for dynamic classes.
  1489. """
  1490. return model
  1491. def model_unpickle(model_id, attrs, factory):
  1492. """
  1493. Used to unpickle Model subclasses with deferred fields.
  1494. """
  1495. if isinstance(model_id, tuple):
  1496. if not apps.ready:
  1497. apps.populate(settings.INSTALLED_APPS)
  1498. model = apps.get_model(*model_id)
  1499. else:
  1500. # Backwards compat - the model was cached directly in earlier versions.
  1501. model = model_id
  1502. cls = factory(model, attrs)
  1503. return cls.__new__(cls)
  1504. model_unpickle.__safe_for_unpickle__ = True
  1505. def unpickle_inner_exception(klass, exception_name):
  1506. # Get the exception class from the class it is attached to:
  1507. exception = getattr(klass, exception_name)
  1508. return exception.__new__(exception)