base.py 77 KB

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