base.py 69 KB

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