You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.py 74KB

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