base.py 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531
  1. import copy
  2. import inspect
  3. import warnings
  4. from functools import partialmethod
  5. from itertools import chain
  6. from asgiref.sync import sync_to_async
  7. import django
  8. from django.apps import apps
  9. from django.conf import settings
  10. from django.core import checks
  11. from django.core.exceptions import (
  12. NON_FIELD_ERRORS,
  13. FieldDoesNotExist,
  14. FieldError,
  15. MultipleObjectsReturned,
  16. ObjectDoesNotExist,
  17. ValidationError,
  18. )
  19. from django.db import (
  20. DJANGO_VERSION_PICKLE_KEY,
  21. DatabaseError,
  22. connection,
  23. connections,
  24. router,
  25. transaction,
  26. )
  27. from django.db.models import NOT_PROVIDED, ExpressionWrapper, IntegerField, Max, Value
  28. from django.db.models.constants import LOOKUP_SEP
  29. from django.db.models.constraints import CheckConstraint, UniqueConstraint
  30. from django.db.models.deletion import CASCADE, Collector
  31. from django.db.models.expressions import RawSQL
  32. from django.db.models.fields.related import (
  33. ForeignObjectRel,
  34. OneToOneField,
  35. lazy_related_operation,
  36. resolve_relation,
  37. )
  38. from django.db.models.functions import Coalesce
  39. from django.db.models.manager import Manager
  40. from django.db.models.options import Options
  41. from django.db.models.query import F, Q
  42. from django.db.models.signals import (
  43. class_prepared,
  44. post_init,
  45. post_save,
  46. pre_init,
  47. pre_save,
  48. )
  49. from django.db.models.utils import AltersData, make_model_tuple
  50. from django.utils.encoding import force_str
  51. from django.utils.hashable import make_hashable
  52. from django.utils.text import capfirst, get_text_list
  53. from django.utils.translation import gettext_lazy as _
  54. class Deferred:
  55. def __repr__(self):
  56. return "<Deferred field>"
  57. def __str__(self):
  58. return "<Deferred field>"
  59. DEFERRED = Deferred()
  60. def subclass_exception(name, bases, module, attached_to):
  61. """
  62. Create exception subclass. Used by ModelBase below.
  63. The exception is created in a way that allows it to be pickled, assuming
  64. that the returned exception class will be added as an attribute to the
  65. 'attached_to' class.
  66. """
  67. return type(
  68. name,
  69. bases,
  70. {
  71. "__module__": module,
  72. "__qualname__": "%s.%s" % (attached_to.__qualname__, name),
  73. },
  74. )
  75. def _has_contribute_to_class(value):
  76. # Only call contribute_to_class() if it's bound.
  77. return not inspect.isclass(value) and hasattr(value, "contribute_to_class")
  78. class ModelBase(type):
  79. """Metaclass for all models."""
  80. def __new__(cls, name, bases, attrs, **kwargs):
  81. super_new = super().__new__
  82. # Also ensure initialization is only performed for subclasses of Model
  83. # (excluding Model class itself).
  84. parents = [b for b in bases if isinstance(b, ModelBase)]
  85. if not parents:
  86. return super_new(cls, name, bases, attrs)
  87. # Create the class.
  88. module = attrs.pop("__module__")
  89. new_attrs = {"__module__": module}
  90. classcell = attrs.pop("__classcell__", None)
  91. if classcell is not None:
  92. new_attrs["__classcell__"] = classcell
  93. attr_meta = attrs.pop("Meta", None)
  94. # Pass all attrs without a (Django-specific) contribute_to_class()
  95. # method to type.__new__() so that they're properly initialized
  96. # (i.e. __set_name__()).
  97. contributable_attrs = {}
  98. for obj_name, obj in attrs.items():
  99. if _has_contribute_to_class(obj):
  100. contributable_attrs[obj_name] = obj
  101. else:
  102. new_attrs[obj_name] = obj
  103. new_class = super_new(cls, name, bases, new_attrs, **kwargs)
  104. abstract = getattr(attr_meta, "abstract", False)
  105. meta = attr_meta or getattr(new_class, "Meta", None)
  106. base_meta = getattr(new_class, "_meta", None)
  107. app_label = None
  108. # Look for an application configuration to attach the model to.
  109. app_config = apps.get_containing_app_config(module)
  110. if getattr(meta, "app_label", None) is None:
  111. if app_config is None:
  112. if not abstract:
  113. raise RuntimeError(
  114. "Model class %s.%s doesn't declare an explicit "
  115. "app_label and isn't in an application in "
  116. "INSTALLED_APPS." % (module, name)
  117. )
  118. else:
  119. app_label = app_config.label
  120. new_class.add_to_class("_meta", Options(meta, app_label))
  121. if not abstract:
  122. new_class.add_to_class(
  123. "DoesNotExist",
  124. subclass_exception(
  125. "DoesNotExist",
  126. tuple(
  127. x.DoesNotExist
  128. for x in parents
  129. if hasattr(x, "_meta") and not x._meta.abstract
  130. )
  131. or (ObjectDoesNotExist,),
  132. module,
  133. attached_to=new_class,
  134. ),
  135. )
  136. new_class.add_to_class(
  137. "MultipleObjectsReturned",
  138. subclass_exception(
  139. "MultipleObjectsReturned",
  140. tuple(
  141. x.MultipleObjectsReturned
  142. for x in parents
  143. if hasattr(x, "_meta") and not x._meta.abstract
  144. )
  145. or (MultipleObjectsReturned,),
  146. module,
  147. attached_to=new_class,
  148. ),
  149. )
  150. if base_meta and not base_meta.abstract:
  151. # Non-abstract child classes inherit some attributes from their
  152. # non-abstract parent (unless an ABC comes before it in the
  153. # method resolution order).
  154. if not hasattr(meta, "ordering"):
  155. new_class._meta.ordering = base_meta.ordering
  156. if not hasattr(meta, "get_latest_by"):
  157. new_class._meta.get_latest_by = base_meta.get_latest_by
  158. is_proxy = new_class._meta.proxy
  159. # If the model is a proxy, ensure that the base class
  160. # hasn't been swapped out.
  161. if is_proxy and base_meta and base_meta.swapped:
  162. raise TypeError(
  163. "%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped)
  164. )
  165. # Add remaining attributes (those with a contribute_to_class() method)
  166. # to the class.
  167. for obj_name, obj in contributable_attrs.items():
  168. new_class.add_to_class(obj_name, obj)
  169. # All the fields of any type declared on this model
  170. new_fields = chain(
  171. new_class._meta.local_fields,
  172. new_class._meta.local_many_to_many,
  173. new_class._meta.private_fields,
  174. )
  175. field_names = {f.name for f in new_fields}
  176. # Basic setup for proxy models.
  177. if is_proxy:
  178. base = None
  179. for parent in [kls for kls in parents if hasattr(kls, "_meta")]:
  180. if parent._meta.abstract:
  181. if parent._meta.fields:
  182. raise TypeError(
  183. "Abstract base class containing model fields not "
  184. "permitted for proxy model '%s'." % name
  185. )
  186. else:
  187. continue
  188. if base is None:
  189. base = parent
  190. elif parent._meta.concrete_model is not base._meta.concrete_model:
  191. raise TypeError(
  192. "Proxy model '%s' has more than one non-abstract model base "
  193. "class." % name
  194. )
  195. if base is None:
  196. raise TypeError(
  197. "Proxy model '%s' has no non-abstract model base class." % name
  198. )
  199. new_class._meta.setup_proxy(base)
  200. new_class._meta.concrete_model = base._meta.concrete_model
  201. else:
  202. new_class._meta.concrete_model = new_class
  203. # Collect the parent links for multi-table inheritance.
  204. parent_links = {}
  205. for base in reversed([new_class] + parents):
  206. # Conceptually equivalent to `if base is Model`.
  207. if not hasattr(base, "_meta"):
  208. continue
  209. # Skip concrete parent classes.
  210. if base != new_class and not base._meta.abstract:
  211. continue
  212. # Locate OneToOneField instances.
  213. for field in base._meta.local_fields:
  214. if isinstance(field, OneToOneField) and field.remote_field.parent_link:
  215. related = resolve_relation(new_class, field.remote_field.model)
  216. parent_links[make_model_tuple(related)] = field
  217. # Track fields inherited from base models.
  218. inherited_attributes = set()
  219. # Do the appropriate setup for any model parents.
  220. for base in new_class.mro():
  221. if base not in parents or not hasattr(base, "_meta"):
  222. # Things without _meta aren't functional models, so they're
  223. # uninteresting parents.
  224. inherited_attributes.update(base.__dict__)
  225. continue
  226. parent_fields = base._meta.local_fields + base._meta.local_many_to_many
  227. if not base._meta.abstract:
  228. # Check for clashes between locally declared fields and those
  229. # on the base classes.
  230. for field in parent_fields:
  231. if field.name in field_names:
  232. raise FieldError(
  233. "Local field %r in class %r clashes with field of "
  234. "the same name from base class %r."
  235. % (
  236. field.name,
  237. name,
  238. base.__name__,
  239. )
  240. )
  241. else:
  242. inherited_attributes.add(field.name)
  243. # Concrete classes...
  244. base = base._meta.concrete_model
  245. base_key = make_model_tuple(base)
  246. if base_key in parent_links:
  247. field = parent_links[base_key]
  248. elif not is_proxy:
  249. attr_name = "%s_ptr" % base._meta.model_name
  250. field = OneToOneField(
  251. base,
  252. on_delete=CASCADE,
  253. name=attr_name,
  254. auto_created=True,
  255. parent_link=True,
  256. )
  257. if attr_name in field_names:
  258. raise FieldError(
  259. "Auto-generated field '%s' in class %r for "
  260. "parent_link to base class %r clashes with "
  261. "declared field of the same name."
  262. % (
  263. attr_name,
  264. name,
  265. base.__name__,
  266. )
  267. )
  268. # Only add the ptr field if it's not already present;
  269. # e.g. migrations will already have it specified
  270. if not hasattr(new_class, attr_name):
  271. new_class.add_to_class(attr_name, field)
  272. else:
  273. field = None
  274. new_class._meta.parents[base] = field
  275. else:
  276. base_parents = base._meta.parents.copy()
  277. # Add fields from abstract base class if it wasn't overridden.
  278. for field in parent_fields:
  279. if (
  280. field.name not in field_names
  281. and field.name not in new_class.__dict__
  282. and field.name not in inherited_attributes
  283. ):
  284. new_field = copy.deepcopy(field)
  285. new_class.add_to_class(field.name, new_field)
  286. # Replace parent links defined on this base by the new
  287. # field. It will be appropriately resolved if required.
  288. if field.one_to_one:
  289. for parent, parent_link in base_parents.items():
  290. if field == parent_link:
  291. base_parents[parent] = new_field
  292. # Pass any non-abstract parent classes onto child.
  293. new_class._meta.parents.update(base_parents)
  294. # Inherit private fields (like GenericForeignKey) from the parent
  295. # class
  296. for field in base._meta.private_fields:
  297. if field.name in field_names:
  298. if not base._meta.abstract:
  299. raise FieldError(
  300. "Local field %r in class %r clashes with field of "
  301. "the same name from base class %r."
  302. % (
  303. field.name,
  304. name,
  305. base.__name__,
  306. )
  307. )
  308. else:
  309. field = copy.deepcopy(field)
  310. if not base._meta.abstract:
  311. field.mti_inherited = True
  312. new_class.add_to_class(field.name, field)
  313. # Copy indexes so that index names are unique when models extend an
  314. # abstract model.
  315. new_class._meta.indexes = [
  316. copy.deepcopy(idx) for idx in new_class._meta.indexes
  317. ]
  318. if abstract:
  319. # Abstract base models can't be instantiated and don't appear in
  320. # the list of models for an app. We do the final setup for them a
  321. # little differently from normal models.
  322. attr_meta.abstract = False
  323. new_class.Meta = attr_meta
  324. return new_class
  325. new_class._prepare()
  326. new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
  327. return new_class
  328. def add_to_class(cls, name, value):
  329. if _has_contribute_to_class(value):
  330. value.contribute_to_class(cls, name)
  331. else:
  332. setattr(cls, name, value)
  333. def _prepare(cls):
  334. """Create some methods once self._meta has been populated."""
  335. opts = cls._meta
  336. opts._prepare(cls)
  337. if opts.order_with_respect_to:
  338. cls.get_next_in_order = partialmethod(
  339. cls._get_next_or_previous_in_order, is_next=True
  340. )
  341. cls.get_previous_in_order = partialmethod(
  342. cls._get_next_or_previous_in_order, is_next=False
  343. )
  344. # Defer creating accessors on the foreign class until it has been
  345. # created and registered. If remote_field is None, we're ordering
  346. # with respect to a GenericForeignKey and don't know what the
  347. # foreign class is - we'll add those accessors later in
  348. # contribute_to_class().
  349. if opts.order_with_respect_to.remote_field:
  350. wrt = opts.order_with_respect_to
  351. remote = wrt.remote_field.model
  352. lazy_related_operation(make_foreign_order_accessors, cls, remote)
  353. # Give the class a docstring -- its definition.
  354. if cls.__doc__ is None:
  355. cls.__doc__ = "%s(%s)" % (
  356. cls.__name__,
  357. ", ".join(f.name for f in opts.fields),
  358. )
  359. get_absolute_url_override = settings.ABSOLUTE_URL_OVERRIDES.get(
  360. opts.label_lower
  361. )
  362. if get_absolute_url_override:
  363. setattr(cls, "get_absolute_url", get_absolute_url_override)
  364. if not opts.managers:
  365. if any(f.name == "objects" for f in opts.fields):
  366. raise ValueError(
  367. "Model %s must specify a custom Manager, because it has a "
  368. "field named 'objects'." % cls.__name__
  369. )
  370. manager = Manager()
  371. manager.auto_created = True
  372. cls.add_to_class("objects", manager)
  373. # Set the name of _meta.indexes. This can't be done in
  374. # Options.contribute_to_class() because fields haven't been added to
  375. # the model at that point.
  376. for index in cls._meta.indexes:
  377. if not index.name:
  378. index.set_name_with_model(cls)
  379. class_prepared.send(sender=cls)
  380. @property
  381. def _base_manager(cls):
  382. return cls._meta.base_manager
  383. @property
  384. def _default_manager(cls):
  385. return cls._meta.default_manager
  386. class ModelStateFieldsCacheDescriptor:
  387. def __get__(self, instance, cls=None):
  388. if instance is None:
  389. return self
  390. res = instance.fields_cache = {}
  391. return res
  392. class ModelState:
  393. """Store model instance state."""
  394. db = None
  395. # If true, uniqueness validation checks will consider this a new, unsaved
  396. # object. Necessary for correct validation of new instances of objects with
  397. # explicit (non-auto) PKs. This impacts validation only; it has no effect
  398. # on the actual save.
  399. adding = True
  400. fields_cache = ModelStateFieldsCacheDescriptor()
  401. class Model(AltersData, metaclass=ModelBase):
  402. def __init__(self, *args, **kwargs):
  403. # Alias some things as locals to avoid repeat global lookups
  404. cls = self.__class__
  405. opts = self._meta
  406. _setattr = setattr
  407. _DEFERRED = DEFERRED
  408. if opts.abstract:
  409. raise TypeError("Abstract models cannot be instantiated.")
  410. pre_init.send(sender=cls, args=args, kwargs=kwargs)
  411. # Set up the storage for instance state
  412. self._state = ModelState()
  413. # There is a rather weird disparity here; if kwargs, it's set, then args
  414. # overrides it. It should be one or the other; don't duplicate the work
  415. # The reason for the kwargs check is that standard iterator passes in by
  416. # args, and instantiation for iteration is 33% faster.
  417. if len(args) > len(opts.concrete_fields):
  418. # Daft, but matches old exception sans the err msg.
  419. raise IndexError("Number of args exceeds number of fields")
  420. if not kwargs:
  421. fields_iter = iter(opts.concrete_fields)
  422. # The ordering of the zip calls matter - zip throws StopIteration
  423. # when an iter throws it. So if the first iter throws it, the second
  424. # is *not* consumed. We rely on this, so don't change the order
  425. # without changing the logic.
  426. for val, field in zip(args, fields_iter):
  427. if val is _DEFERRED:
  428. continue
  429. _setattr(self, field.attname, val)
  430. else:
  431. # Slower, kwargs-ready version.
  432. fields_iter = iter(opts.fields)
  433. for val, field in zip(args, fields_iter):
  434. if val is _DEFERRED:
  435. continue
  436. _setattr(self, field.attname, val)
  437. if kwargs.pop(field.name, NOT_PROVIDED) is not NOT_PROVIDED:
  438. raise TypeError(
  439. f"{cls.__qualname__}() got both positional and "
  440. f"keyword arguments for field '{field.name}'."
  441. )
  442. # Now we're left with the unprocessed fields that *must* come from
  443. # keywords, or default.
  444. for field in fields_iter:
  445. is_related_object = False
  446. # Virtual field
  447. if field.attname not in kwargs and field.column is None:
  448. continue
  449. if kwargs:
  450. if isinstance(field.remote_field, ForeignObjectRel):
  451. try:
  452. # Assume object instance was passed in.
  453. rel_obj = kwargs.pop(field.name)
  454. is_related_object = True
  455. except KeyError:
  456. try:
  457. # Object instance wasn't passed in -- must be an ID.
  458. val = kwargs.pop(field.attname)
  459. except KeyError:
  460. val = field.get_default()
  461. else:
  462. try:
  463. val = kwargs.pop(field.attname)
  464. except KeyError:
  465. # This is done with an exception rather than the
  466. # default argument on pop because we don't want
  467. # get_default() to be evaluated, and then not used.
  468. # Refs #12057.
  469. val = field.get_default()
  470. else:
  471. val = field.get_default()
  472. if is_related_object:
  473. # If we are passed a related instance, set it using the
  474. # field.name instead of field.attname (e.g. "user" instead of
  475. # "user_id") so that the object gets properly cached (and type
  476. # checked) by the RelatedObjectDescriptor.
  477. if rel_obj is not _DEFERRED:
  478. _setattr(self, field.name, rel_obj)
  479. else:
  480. if val is not _DEFERRED:
  481. _setattr(self, field.attname, val)
  482. if kwargs:
  483. property_names = opts._property_names
  484. unexpected = ()
  485. for prop, value in kwargs.items():
  486. # Any remaining kwargs must correspond to properties or virtual
  487. # fields.
  488. if prop in property_names:
  489. if value is not _DEFERRED:
  490. _setattr(self, prop, value)
  491. else:
  492. try:
  493. opts.get_field(prop)
  494. except FieldDoesNotExist:
  495. unexpected += (prop,)
  496. else:
  497. if value is not _DEFERRED:
  498. _setattr(self, prop, value)
  499. if unexpected:
  500. unexpected_names = ", ".join(repr(n) for n in unexpected)
  501. raise TypeError(
  502. f"{cls.__name__}() got unexpected keyword arguments: "
  503. f"{unexpected_names}"
  504. )
  505. super().__init__()
  506. post_init.send(sender=cls, instance=self)
  507. @classmethod
  508. def from_db(cls, db, field_names, values):
  509. if len(values) != len(cls._meta.concrete_fields):
  510. values_iter = iter(values)
  511. values = [
  512. next(values_iter) if f.attname in field_names else DEFERRED
  513. for f in cls._meta.concrete_fields
  514. ]
  515. new = cls(*values)
  516. new._state.adding = False
  517. new._state.db = db
  518. return new
  519. def __repr__(self):
  520. return "<%s: %s>" % (self.__class__.__name__, self)
  521. def __str__(self):
  522. return "%s object (%s)" % (self.__class__.__name__, self.pk)
  523. def __eq__(self, other):
  524. if not isinstance(other, Model):
  525. return NotImplemented
  526. if self._meta.concrete_model != other._meta.concrete_model:
  527. return False
  528. my_pk = self.pk
  529. if my_pk is None:
  530. return self is other
  531. return my_pk == other.pk
  532. def __hash__(self):
  533. if self.pk is None:
  534. raise TypeError("Model instances without primary key value are unhashable")
  535. return hash(self.pk)
  536. def __reduce__(self):
  537. data = self.__getstate__()
  538. data[DJANGO_VERSION_PICKLE_KEY] = django.__version__
  539. class_id = self._meta.app_label, self._meta.object_name
  540. return model_unpickle, (class_id,), data
  541. def __getstate__(self):
  542. """Hook to allow choosing the attributes to pickle."""
  543. state = self.__dict__.copy()
  544. state["_state"] = copy.copy(state["_state"])
  545. state["_state"].fields_cache = state["_state"].fields_cache.copy()
  546. # memoryview cannot be pickled, so cast it to bytes and store
  547. # separately.
  548. _memoryview_attrs = []
  549. for attr, value in state.items():
  550. if isinstance(value, memoryview):
  551. _memoryview_attrs.append((attr, bytes(value)))
  552. if _memoryview_attrs:
  553. state["_memoryview_attrs"] = _memoryview_attrs
  554. for attr, value in _memoryview_attrs:
  555. state.pop(attr)
  556. return state
  557. def __setstate__(self, state):
  558. pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)
  559. if pickled_version:
  560. if pickled_version != django.__version__:
  561. warnings.warn(
  562. "Pickled model instance's Django version %s does not "
  563. "match the current version %s."
  564. % (pickled_version, django.__version__),
  565. RuntimeWarning,
  566. stacklevel=2,
  567. )
  568. else:
  569. warnings.warn(
  570. "Pickled model instance's Django version is not specified.",
  571. RuntimeWarning,
  572. stacklevel=2,
  573. )
  574. if "_memoryview_attrs" in state:
  575. for attr, value in state.pop("_memoryview_attrs"):
  576. state[attr] = memoryview(value)
  577. self.__dict__.update(state)
  578. def _get_pk_val(self, meta=None):
  579. meta = meta or self._meta
  580. return getattr(self, meta.pk.attname)
  581. def _set_pk_val(self, value):
  582. for parent_link in self._meta.parents.values():
  583. if parent_link and parent_link != self._meta.pk:
  584. setattr(self, parent_link.target_field.attname, value)
  585. return setattr(self, self._meta.pk.attname, value)
  586. pk = property(_get_pk_val, _set_pk_val)
  587. def get_deferred_fields(self):
  588. """
  589. Return a set containing names of deferred fields for this instance.
  590. """
  591. return {
  592. f.attname
  593. for f in self._meta.concrete_fields
  594. if f.attname not in self.__dict__
  595. }
  596. def refresh_from_db(self, using=None, fields=None):
  597. """
  598. Reload field values from the database.
  599. By default, the reloading happens from the database this instance was
  600. loaded from, or by the read router if this instance wasn't loaded from
  601. any database. The using parameter will override the default.
  602. Fields can be used to specify which fields to reload. The fields
  603. should be an iterable of field attnames. If fields is None, then
  604. all non-deferred fields are reloaded.
  605. When accessing deferred fields of an instance, the deferred loading
  606. of the field will call this method.
  607. """
  608. if fields is None:
  609. self._prefetched_objects_cache = {}
  610. else:
  611. prefetched_objects_cache = getattr(self, "_prefetched_objects_cache", ())
  612. for field in fields:
  613. if field in prefetched_objects_cache:
  614. del prefetched_objects_cache[field]
  615. fields.remove(field)
  616. if not fields:
  617. return
  618. if any(LOOKUP_SEP in f for f in fields):
  619. raise ValueError(
  620. 'Found "%s" in fields argument. Relations and transforms '
  621. "are not allowed in fields." % LOOKUP_SEP
  622. )
  623. hints = {"instance": self}
  624. db_instance_qs = self.__class__._base_manager.db_manager(
  625. using, hints=hints
  626. ).filter(pk=self.pk)
  627. # Use provided fields, if not set then reload all non-deferred fields.
  628. deferred_fields = self.get_deferred_fields()
  629. if fields is not None:
  630. fields = list(fields)
  631. db_instance_qs = db_instance_qs.only(*fields)
  632. elif deferred_fields:
  633. fields = [
  634. f.attname
  635. for f in self._meta.concrete_fields
  636. if f.attname not in deferred_fields
  637. ]
  638. db_instance_qs = db_instance_qs.only(*fields)
  639. db_instance = db_instance_qs.get()
  640. non_loaded_fields = db_instance.get_deferred_fields()
  641. for field in self._meta.concrete_fields:
  642. if field.attname in non_loaded_fields:
  643. # This field wasn't refreshed - skip ahead.
  644. continue
  645. setattr(self, field.attname, getattr(db_instance, field.attname))
  646. # Clear cached foreign keys.
  647. if field.is_relation and field.is_cached(self):
  648. field.delete_cached_value(self)
  649. # Clear cached relations.
  650. for field in self._meta.related_objects:
  651. if field.is_cached(self):
  652. field.delete_cached_value(self)
  653. # Clear cached private relations.
  654. for field in self._meta.private_fields:
  655. if field.is_relation and field.is_cached(self):
  656. field.delete_cached_value(self)
  657. self._state.db = db_instance._state.db
  658. async def arefresh_from_db(self, using=None, fields=None):
  659. return await sync_to_async(self.refresh_from_db)(using=using, fields=fields)
  660. def serializable_value(self, field_name):
  661. """
  662. Return the value of the field name for this instance. If the field is
  663. a foreign key, return the id value instead of the object. If there's
  664. no Field object with this name on the model, return the model
  665. attribute's value.
  666. Used to serialize a field's value (in the serializer, or form output,
  667. for example). Normally, you would just access the attribute directly
  668. and not use this method.
  669. """
  670. try:
  671. field = self._meta.get_field(field_name)
  672. except FieldDoesNotExist:
  673. return getattr(self, field_name)
  674. return getattr(self, field.attname)
  675. def save(
  676. self, force_insert=False, force_update=False, using=None, update_fields=None
  677. ):
  678. """
  679. Save the current instance. Override this in a subclass if you want to
  680. control the saving process.
  681. The 'force_insert' and 'force_update' parameters can be used to insist
  682. that the "save" must be an SQL insert or update (or equivalent for
  683. non-SQL backends), respectively. Normally, they should not be set.
  684. """
  685. self._prepare_related_fields_for_save(operation_name="save")
  686. using = using or router.db_for_write(self.__class__, instance=self)
  687. if force_insert and (force_update or update_fields):
  688. raise ValueError("Cannot force both insert and updating in model saving.")
  689. deferred_fields = self.get_deferred_fields()
  690. if update_fields is not None:
  691. # If update_fields is empty, skip the save. We do also check for
  692. # no-op saves later on for inheritance cases. This bailout is
  693. # still needed for skipping signal sending.
  694. if not update_fields:
  695. return
  696. update_fields = frozenset(update_fields)
  697. field_names = self._meta._non_pk_concrete_field_names
  698. non_model_fields = update_fields.difference(field_names)
  699. if non_model_fields:
  700. raise ValueError(
  701. "The following fields do not exist in this model, are m2m "
  702. "fields, or are non-concrete fields: %s"
  703. % ", ".join(non_model_fields)
  704. )
  705. # If saving to the same database, and this model is deferred, then
  706. # automatically do an "update_fields" save on the loaded fields.
  707. elif not force_insert and deferred_fields and using == self._state.db:
  708. field_names = set()
  709. for field in self._meta.concrete_fields:
  710. if not field.primary_key and not hasattr(field, "through"):
  711. field_names.add(field.attname)
  712. loaded_fields = field_names.difference(deferred_fields)
  713. if loaded_fields:
  714. update_fields = frozenset(loaded_fields)
  715. self.save_base(
  716. using=using,
  717. force_insert=force_insert,
  718. force_update=force_update,
  719. update_fields=update_fields,
  720. )
  721. save.alters_data = True
  722. async def asave(
  723. self, force_insert=False, force_update=False, using=None, update_fields=None
  724. ):
  725. return await sync_to_async(self.save)(
  726. force_insert=force_insert,
  727. force_update=force_update,
  728. using=using,
  729. update_fields=update_fields,
  730. )
  731. asave.alters_data = True
  732. def save_base(
  733. self,
  734. raw=False,
  735. force_insert=False,
  736. force_update=False,
  737. using=None,
  738. update_fields=None,
  739. ):
  740. """
  741. Handle the parts of saving which should be done only once per save,
  742. yet need to be done in raw saves, too. This includes some sanity
  743. checks and signal sending.
  744. The 'raw' argument is telling save_base not to save any parent
  745. models and not to do any changes to the values before save. This
  746. is used by fixture loading.
  747. """
  748. using = using or router.db_for_write(self.__class__, instance=self)
  749. assert not (force_insert and (force_update or update_fields))
  750. assert update_fields is None or update_fields
  751. cls = origin = self.__class__
  752. # Skip proxies, but keep the origin as the proxy model.
  753. if cls._meta.proxy:
  754. cls = cls._meta.concrete_model
  755. meta = cls._meta
  756. if not meta.auto_created:
  757. pre_save.send(
  758. sender=origin,
  759. instance=self,
  760. raw=raw,
  761. using=using,
  762. update_fields=update_fields,
  763. )
  764. # A transaction isn't needed if one query is issued.
  765. if meta.parents:
  766. context_manager = transaction.atomic(using=using, savepoint=False)
  767. else:
  768. context_manager = transaction.mark_for_rollback_on_error(using=using)
  769. with context_manager:
  770. parent_inserted = False
  771. if not raw:
  772. parent_inserted = self._save_parents(cls, using, update_fields)
  773. updated = self._save_table(
  774. raw,
  775. cls,
  776. force_insert or parent_inserted,
  777. force_update,
  778. using,
  779. update_fields,
  780. )
  781. # Store the database on which the object was saved
  782. self._state.db = using
  783. # Once saved, this is no longer a to-be-added instance.
  784. self._state.adding = False
  785. # Signal that the save is complete
  786. if not meta.auto_created:
  787. post_save.send(
  788. sender=origin,
  789. instance=self,
  790. created=(not updated),
  791. update_fields=update_fields,
  792. raw=raw,
  793. using=using,
  794. )
  795. save_base.alters_data = True
  796. def _save_parents(self, cls, using, update_fields):
  797. """Save all the parents of cls using values from self."""
  798. meta = cls._meta
  799. inserted = False
  800. for parent, field in meta.parents.items():
  801. # Make sure the link fields are synced between parent and self.
  802. if (
  803. field
  804. and getattr(self, parent._meta.pk.attname) is None
  805. and getattr(self, field.attname) is not None
  806. ):
  807. setattr(self, parent._meta.pk.attname, getattr(self, field.attname))
  808. parent_inserted = self._save_parents(
  809. cls=parent, using=using, update_fields=update_fields
  810. )
  811. updated = self._save_table(
  812. cls=parent,
  813. using=using,
  814. update_fields=update_fields,
  815. force_insert=parent_inserted,
  816. )
  817. if not updated:
  818. inserted = True
  819. # Set the parent's PK value to self.
  820. if field:
  821. setattr(self, field.attname, self._get_pk_val(parent._meta))
  822. # Since we didn't have an instance of the parent handy set
  823. # attname directly, bypassing the descriptor. Invalidate
  824. # the related object cache, in case it's been accidentally
  825. # populated. A fresh instance will be re-built from the
  826. # database if necessary.
  827. if field.is_cached(self):
  828. field.delete_cached_value(self)
  829. return inserted
  830. def _save_table(
  831. self,
  832. raw=False,
  833. cls=None,
  834. force_insert=False,
  835. force_update=False,
  836. using=None,
  837. update_fields=None,
  838. ):
  839. """
  840. Do the heavy-lifting involved in saving. Update or insert the data
  841. for a single table.
  842. """
  843. meta = cls._meta
  844. non_pks = [f for f in meta.local_concrete_fields if not f.primary_key]
  845. if update_fields:
  846. non_pks = [
  847. f
  848. for f in non_pks
  849. if f.name in update_fields or f.attname in update_fields
  850. ]
  851. pk_val = self._get_pk_val(meta)
  852. if pk_val is None:
  853. pk_val = meta.pk.get_pk_value_on_save(self)
  854. setattr(self, meta.pk.attname, pk_val)
  855. pk_set = pk_val is not None
  856. if not pk_set and (force_update or update_fields):
  857. raise ValueError("Cannot force an update in save() with no primary key.")
  858. updated = False
  859. # Skip an UPDATE when adding an instance and primary key has a default.
  860. if (
  861. not raw
  862. and not force_insert
  863. and self._state.adding
  864. and meta.pk.default
  865. and meta.pk.default is not NOT_PROVIDED
  866. ):
  867. force_insert = True
  868. # If possible, try an UPDATE. If that doesn't update anything, do an INSERT.
  869. if pk_set and not force_insert:
  870. base_qs = cls._base_manager.using(using)
  871. values = [
  872. (
  873. f,
  874. None,
  875. (getattr(self, f.attname) if raw else f.pre_save(self, False)),
  876. )
  877. for f in non_pks
  878. ]
  879. forced_update = update_fields or force_update
  880. updated = self._do_update(
  881. base_qs, using, pk_val, values, update_fields, forced_update
  882. )
  883. if force_update and not updated:
  884. raise DatabaseError("Forced update did not affect any rows.")
  885. if update_fields and not updated:
  886. raise DatabaseError("Save with update_fields did not affect any rows.")
  887. if not updated:
  888. if meta.order_with_respect_to:
  889. # If this is a model with an order_with_respect_to
  890. # autopopulate the _order field
  891. field = meta.order_with_respect_to
  892. filter_args = field.get_filter_kwargs_for_object(self)
  893. self._order = (
  894. cls._base_manager.using(using)
  895. .filter(**filter_args)
  896. .aggregate(
  897. _order__max=Coalesce(
  898. ExpressionWrapper(
  899. Max("_order") + Value(1), output_field=IntegerField()
  900. ),
  901. Value(0),
  902. ),
  903. )["_order__max"]
  904. )
  905. fields = meta.local_concrete_fields
  906. if not pk_set:
  907. fields = [f for f in fields if f is not meta.auto_field]
  908. returning_fields = meta.db_returning_fields
  909. results = self._do_insert(
  910. cls._base_manager, using, fields, returning_fields, raw
  911. )
  912. if results:
  913. for value, field in zip(results[0], returning_fields):
  914. setattr(self, field.attname, value)
  915. return updated
  916. def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update):
  917. """
  918. Try to update the model. Return True if the model was updated (if an
  919. update query was done and a matching row was found in the DB).
  920. """
  921. filtered = base_qs.filter(pk=pk_val)
  922. if not values:
  923. # We can end up here when saving a model in inheritance chain where
  924. # update_fields doesn't target any field in current model. In that
  925. # case we just say the update succeeded. Another case ending up here
  926. # is a model with just PK - in that case check that the PK still
  927. # exists.
  928. return update_fields is not None or filtered.exists()
  929. if self._meta.select_on_save and not forced_update:
  930. return (
  931. filtered.exists()
  932. and
  933. # It may happen that the object is deleted from the DB right after
  934. # this check, causing the subsequent UPDATE to return zero matching
  935. # rows. The same result can occur in some rare cases when the
  936. # database returns zero despite the UPDATE being executed
  937. # successfully (a row is matched and updated). In order to
  938. # distinguish these two cases, the object's existence in the
  939. # database is again checked for if the UPDATE query returns 0.
  940. (filtered._update(values) > 0 or filtered.exists())
  941. )
  942. return filtered._update(values) > 0
  943. def _do_insert(self, manager, using, fields, returning_fields, raw):
  944. """
  945. Do an INSERT. If returning_fields is defined then this method should
  946. return the newly created data for the model.
  947. """
  948. return manager._insert(
  949. [self],
  950. fields=fields,
  951. returning_fields=returning_fields,
  952. using=using,
  953. raw=raw,
  954. )
  955. def _prepare_related_fields_for_save(self, operation_name, fields=None):
  956. # Ensure that a model instance without a PK hasn't been assigned to
  957. # a ForeignKey, GenericForeignKey or OneToOneField on this model. If
  958. # the field is nullable, allowing the save would result in silent data
  959. # loss.
  960. for field in self._meta.concrete_fields:
  961. if fields and field not in fields:
  962. continue
  963. # If the related field isn't cached, then an instance hasn't been
  964. # assigned and there's no need to worry about this check.
  965. if field.is_relation and field.is_cached(self):
  966. obj = getattr(self, field.name, None)
  967. if not obj:
  968. continue
  969. # A pk may have been assigned manually to a model instance not
  970. # saved to the database (or auto-generated in a case like
  971. # UUIDField), but we allow the save to proceed and rely on the
  972. # database to raise an IntegrityError if applicable. If
  973. # constraints aren't supported by the database, there's the
  974. # unavoidable risk of data corruption.
  975. if obj.pk is None:
  976. # Remove the object from a related instance cache.
  977. if not field.remote_field.multiple:
  978. field.remote_field.delete_cached_value(obj)
  979. raise ValueError(
  980. "%s() prohibited to prevent data loss due to unsaved "
  981. "related object '%s'." % (operation_name, field.name)
  982. )
  983. elif getattr(self, field.attname) in field.empty_values:
  984. # Set related object if it has been saved after an
  985. # assignment.
  986. setattr(self, field.name, obj)
  987. # If the relationship's pk/to_field was changed, clear the
  988. # cached relationship.
  989. if getattr(obj, field.target_field.attname) != getattr(
  990. self, field.attname
  991. ):
  992. field.delete_cached_value(self)
  993. # GenericForeignKeys are private.
  994. for field in self._meta.private_fields:
  995. if fields and field not in fields:
  996. continue
  997. if (
  998. field.is_relation
  999. and field.is_cached(self)
  1000. and hasattr(field, "fk_field")
  1001. ):
  1002. obj = field.get_cached_value(self, default=None)
  1003. if obj and obj.pk is None:
  1004. raise ValueError(
  1005. f"{operation_name}() prohibited to prevent data loss due to "
  1006. f"unsaved related object '{field.name}'."
  1007. )
  1008. def delete(self, using=None, keep_parents=False):
  1009. if self.pk is None:
  1010. raise ValueError(
  1011. "%s object can't be deleted because its %s attribute is set "
  1012. "to None." % (self._meta.object_name, self._meta.pk.attname)
  1013. )
  1014. using = using or router.db_for_write(self.__class__, instance=self)
  1015. collector = Collector(using=using, origin=self)
  1016. collector.collect([self], keep_parents=keep_parents)
  1017. return collector.delete()
  1018. delete.alters_data = True
  1019. async def adelete(self, using=None, keep_parents=False):
  1020. return await sync_to_async(self.delete)(
  1021. using=using,
  1022. keep_parents=keep_parents,
  1023. )
  1024. adelete.alters_data = True
  1025. def _get_FIELD_display(self, field):
  1026. value = getattr(self, field.attname)
  1027. choices_dict = dict(make_hashable(field.flatchoices))
  1028. # force_str() to coerce lazy strings.
  1029. return force_str(
  1030. choices_dict.get(make_hashable(value), value), strings_only=True
  1031. )
  1032. def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs):
  1033. if not self.pk:
  1034. raise ValueError("get_next/get_previous cannot be used on unsaved objects.")
  1035. op = "gt" if is_next else "lt"
  1036. order = "" if is_next else "-"
  1037. param = getattr(self, field.attname)
  1038. q = Q.create([(field.name, param), (f"pk__{op}", self.pk)], connector=Q.AND)
  1039. q = Q.create([q, (f"{field.name}__{op}", param)], connector=Q.OR)
  1040. qs = (
  1041. self.__class__._default_manager.using(self._state.db)
  1042. .filter(**kwargs)
  1043. .filter(q)
  1044. .order_by("%s%s" % (order, field.name), "%spk" % order)
  1045. )
  1046. try:
  1047. return qs[0]
  1048. except IndexError:
  1049. raise self.DoesNotExist(
  1050. "%s matching query does not exist." % self.__class__._meta.object_name
  1051. )
  1052. def _get_next_or_previous_in_order(self, is_next):
  1053. cachename = "__%s_order_cache" % is_next
  1054. if not hasattr(self, cachename):
  1055. op = "gt" if is_next else "lt"
  1056. order = "_order" if is_next else "-_order"
  1057. order_field = self._meta.order_with_respect_to
  1058. filter_args = order_field.get_filter_kwargs_for_object(self)
  1059. obj = (
  1060. self.__class__._default_manager.filter(**filter_args)
  1061. .filter(
  1062. **{
  1063. "_order__%s"
  1064. % op: self.__class__._default_manager.values("_order").filter(
  1065. **{self._meta.pk.name: self.pk}
  1066. )
  1067. }
  1068. )
  1069. .order_by(order)[:1]
  1070. .get()
  1071. )
  1072. setattr(self, cachename, obj)
  1073. return getattr(self, cachename)
  1074. def _get_field_value_map(self, meta, exclude=None):
  1075. if exclude is None:
  1076. exclude = set()
  1077. meta = meta or self._meta
  1078. return {
  1079. field.name: Value(getattr(self, field.attname), field)
  1080. for field in meta.local_concrete_fields
  1081. if field.name not in exclude
  1082. }
  1083. def prepare_database_save(self, field):
  1084. if self.pk is None:
  1085. raise ValueError(
  1086. "Unsaved model instance %r cannot be used in an ORM query." % self
  1087. )
  1088. return getattr(self, field.remote_field.get_related_field().attname)
  1089. def clean(self):
  1090. """
  1091. Hook for doing any extra model-wide validation after clean() has been
  1092. called on every field by self.clean_fields. Any ValidationError raised
  1093. by this method will not be associated with a particular field; it will
  1094. have a special-case association with the field defined by NON_FIELD_ERRORS.
  1095. """
  1096. pass
  1097. def validate_unique(self, exclude=None):
  1098. """
  1099. Check unique constraints on the model and raise ValidationError if any
  1100. failed.
  1101. """
  1102. unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
  1103. errors = self._perform_unique_checks(unique_checks)
  1104. date_errors = self._perform_date_checks(date_checks)
  1105. for k, v in date_errors.items():
  1106. errors.setdefault(k, []).extend(v)
  1107. if errors:
  1108. raise ValidationError(errors)
  1109. def _get_unique_checks(self, exclude=None, include_meta_constraints=False):
  1110. """
  1111. Return a list of checks to perform. Since validate_unique() could be
  1112. called from a ModelForm, some fields may have been excluded; we can't
  1113. perform a unique check on a model that is missing fields involved
  1114. in that check. Fields that did not validate should also be excluded,
  1115. but they need to be passed in via the exclude argument.
  1116. """
  1117. if exclude is None:
  1118. exclude = set()
  1119. unique_checks = []
  1120. unique_togethers = [(self.__class__, self._meta.unique_together)]
  1121. constraints = []
  1122. if include_meta_constraints:
  1123. constraints = [(self.__class__, self._meta.total_unique_constraints)]
  1124. for parent_class in self._meta.get_parent_list():
  1125. if parent_class._meta.unique_together:
  1126. unique_togethers.append(
  1127. (parent_class, parent_class._meta.unique_together)
  1128. )
  1129. if include_meta_constraints and parent_class._meta.total_unique_constraints:
  1130. constraints.append(
  1131. (parent_class, parent_class._meta.total_unique_constraints)
  1132. )
  1133. for model_class, unique_together in unique_togethers:
  1134. for check in unique_together:
  1135. if not any(name in exclude for name in check):
  1136. # Add the check if the field isn't excluded.
  1137. unique_checks.append((model_class, tuple(check)))
  1138. if include_meta_constraints:
  1139. for model_class, model_constraints in constraints:
  1140. for constraint in model_constraints:
  1141. if not any(name in exclude for name in constraint.fields):
  1142. unique_checks.append((model_class, constraint.fields))
  1143. # These are checks for the unique_for_<date/year/month>.
  1144. date_checks = []
  1145. # Gather a list of checks for fields declared as unique and add them to
  1146. # the list of checks.
  1147. fields_with_class = [(self.__class__, self._meta.local_fields)]
  1148. for parent_class in self._meta.get_parent_list():
  1149. fields_with_class.append((parent_class, parent_class._meta.local_fields))
  1150. for model_class, fields in fields_with_class:
  1151. for f in fields:
  1152. name = f.name
  1153. if name in exclude:
  1154. continue
  1155. if f.unique:
  1156. unique_checks.append((model_class, (name,)))
  1157. if f.unique_for_date and f.unique_for_date not in exclude:
  1158. date_checks.append((model_class, "date", name, f.unique_for_date))
  1159. if f.unique_for_year and f.unique_for_year not in exclude:
  1160. date_checks.append((model_class, "year", name, f.unique_for_year))
  1161. if f.unique_for_month and f.unique_for_month not in exclude:
  1162. date_checks.append((model_class, "month", name, f.unique_for_month))
  1163. return unique_checks, date_checks
  1164. def _perform_unique_checks(self, unique_checks):
  1165. errors = {}
  1166. for model_class, unique_check in unique_checks:
  1167. # Try to look up an existing object with the same values as this
  1168. # object's values for all the unique field.
  1169. lookup_kwargs = {}
  1170. for field_name in unique_check:
  1171. f = self._meta.get_field(field_name)
  1172. lookup_value = getattr(self, f.attname)
  1173. # TODO: Handle multiple backends with different feature flags.
  1174. if lookup_value is None or (
  1175. lookup_value == ""
  1176. and connection.features.interprets_empty_strings_as_nulls
  1177. ):
  1178. # no value, skip the lookup
  1179. continue
  1180. if f.primary_key and not self._state.adding:
  1181. # no need to check for unique primary key when editing
  1182. continue
  1183. lookup_kwargs[str(field_name)] = lookup_value
  1184. # some fields were skipped, no reason to do the check
  1185. if len(unique_check) != len(lookup_kwargs):
  1186. continue
  1187. qs = model_class._default_manager.filter(**lookup_kwargs)
  1188. # Exclude the current object from the query if we are editing an
  1189. # instance (as opposed to creating a new one)
  1190. # Note that we need to use the pk as defined by model_class, not
  1191. # self.pk. These can be different fields because model inheritance
  1192. # allows single model to have effectively multiple primary keys.
  1193. # Refs #17615.
  1194. model_class_pk = self._get_pk_val(model_class._meta)
  1195. if not self._state.adding and model_class_pk is not None:
  1196. qs = qs.exclude(pk=model_class_pk)
  1197. if qs.exists():
  1198. if len(unique_check) == 1:
  1199. key = unique_check[0]
  1200. else:
  1201. key = NON_FIELD_ERRORS
  1202. errors.setdefault(key, []).append(
  1203. self.unique_error_message(model_class, unique_check)
  1204. )
  1205. return errors
  1206. def _perform_date_checks(self, date_checks):
  1207. errors = {}
  1208. for model_class, lookup_type, field, unique_for in date_checks:
  1209. lookup_kwargs = {}
  1210. # there's a ticket to add a date lookup, we can remove this special
  1211. # case if that makes it's way in
  1212. date = getattr(self, unique_for)
  1213. if date is None:
  1214. continue
  1215. if lookup_type == "date":
  1216. lookup_kwargs["%s__day" % unique_for] = date.day
  1217. lookup_kwargs["%s__month" % unique_for] = date.month
  1218. lookup_kwargs["%s__year" % unique_for] = date.year
  1219. else:
  1220. lookup_kwargs["%s__%s" % (unique_for, lookup_type)] = getattr(
  1221. date, lookup_type
  1222. )
  1223. lookup_kwargs[field] = getattr(self, field)
  1224. qs = model_class._default_manager.filter(**lookup_kwargs)
  1225. # Exclude the current object from the query if we are editing an
  1226. # instance (as opposed to creating a new one)
  1227. if not self._state.adding and self.pk is not None:
  1228. qs = qs.exclude(pk=self.pk)
  1229. if qs.exists():
  1230. errors.setdefault(field, []).append(
  1231. self.date_error_message(lookup_type, field, unique_for)
  1232. )
  1233. return errors
  1234. def date_error_message(self, lookup_type, field_name, unique_for):
  1235. opts = self._meta
  1236. field = opts.get_field(field_name)
  1237. return ValidationError(
  1238. message=field.error_messages["unique_for_date"],
  1239. code="unique_for_date",
  1240. params={
  1241. "model": self,
  1242. "model_name": capfirst(opts.verbose_name),
  1243. "lookup_type": lookup_type,
  1244. "field": field_name,
  1245. "field_label": capfirst(field.verbose_name),
  1246. "date_field": unique_for,
  1247. "date_field_label": capfirst(opts.get_field(unique_for).verbose_name),
  1248. },
  1249. )
  1250. def unique_error_message(self, model_class, unique_check):
  1251. opts = model_class._meta
  1252. params = {
  1253. "model": self,
  1254. "model_class": model_class,
  1255. "model_name": capfirst(opts.verbose_name),
  1256. "unique_check": unique_check,
  1257. }
  1258. # A unique field
  1259. if len(unique_check) == 1:
  1260. field = opts.get_field(unique_check[0])
  1261. params["field_label"] = capfirst(field.verbose_name)
  1262. return ValidationError(
  1263. message=field.error_messages["unique"],
  1264. code="unique",
  1265. params=params,
  1266. )
  1267. # unique_together
  1268. else:
  1269. field_labels = [
  1270. capfirst(opts.get_field(f).verbose_name) for f in unique_check
  1271. ]
  1272. params["field_labels"] = get_text_list(field_labels, _("and"))
  1273. return ValidationError(
  1274. message=_("%(model_name)s with this %(field_labels)s already exists."),
  1275. code="unique_together",
  1276. params=params,
  1277. )
  1278. def get_constraints(self):
  1279. constraints = [(self.__class__, self._meta.constraints)]
  1280. for parent_class in self._meta.get_parent_list():
  1281. if parent_class._meta.constraints:
  1282. constraints.append((parent_class, parent_class._meta.constraints))
  1283. return constraints
  1284. def validate_constraints(self, exclude=None):
  1285. constraints = self.get_constraints()
  1286. using = router.db_for_write(self.__class__, instance=self)
  1287. errors = {}
  1288. for model_class, model_constraints in constraints:
  1289. for constraint in model_constraints:
  1290. try:
  1291. constraint.validate(model_class, self, exclude=exclude, using=using)
  1292. except ValidationError as e:
  1293. if (
  1294. getattr(e, "code", None) == "unique"
  1295. and len(constraint.fields) == 1
  1296. ):
  1297. errors.setdefault(constraint.fields[0], []).append(e)
  1298. else:
  1299. errors = e.update_error_dict(errors)
  1300. if errors:
  1301. raise ValidationError(errors)
  1302. def full_clean(self, exclude=None, validate_unique=True, validate_constraints=True):
  1303. """
  1304. Call clean_fields(), clean(), validate_unique(), and
  1305. validate_constraints() on the model. Raise a ValidationError for any
  1306. errors that occur.
  1307. """
  1308. errors = {}
  1309. if exclude is None:
  1310. exclude = set()
  1311. else:
  1312. exclude = set(exclude)
  1313. try:
  1314. self.clean_fields(exclude=exclude)
  1315. except ValidationError as e:
  1316. errors = e.update_error_dict(errors)
  1317. # Form.clean() is run even if other validation fails, so do the
  1318. # same with Model.clean() for consistency.
  1319. try:
  1320. self.clean()
  1321. except ValidationError as e:
  1322. errors = e.update_error_dict(errors)
  1323. # Run unique checks, but only for fields that passed validation.
  1324. if validate_unique:
  1325. for name in errors:
  1326. if name != NON_FIELD_ERRORS and name not in exclude:
  1327. exclude.add(name)
  1328. try:
  1329. self.validate_unique(exclude=exclude)
  1330. except ValidationError as e:
  1331. errors = e.update_error_dict(errors)
  1332. # Run constraints checks, but only for fields that passed validation.
  1333. if validate_constraints:
  1334. for name in errors:
  1335. if name != NON_FIELD_ERRORS and name not in exclude:
  1336. exclude.add(name)
  1337. try:
  1338. self.validate_constraints(exclude=exclude)
  1339. except ValidationError as e:
  1340. errors = e.update_error_dict(errors)
  1341. if errors:
  1342. raise ValidationError(errors)
  1343. def clean_fields(self, exclude=None):
  1344. """
  1345. Clean all fields and raise a ValidationError containing a dict
  1346. of all validation errors if any occur.
  1347. """
  1348. if exclude is None:
  1349. exclude = set()
  1350. errors = {}
  1351. for f in self._meta.fields:
  1352. if f.name in exclude:
  1353. continue
  1354. # Skip validation for empty fields with blank=True. The developer
  1355. # is responsible for making sure they have a valid value.
  1356. raw_value = getattr(self, f.attname)
  1357. if f.blank and raw_value in f.empty_values:
  1358. continue
  1359. try:
  1360. setattr(self, f.attname, f.clean(raw_value, self))
  1361. except ValidationError as e:
  1362. errors[f.name] = e.error_list
  1363. if errors:
  1364. raise ValidationError(errors)
  1365. @classmethod
  1366. def check(cls, **kwargs):
  1367. errors = [
  1368. *cls._check_swappable(),
  1369. *cls._check_model(),
  1370. *cls._check_managers(**kwargs),
  1371. ]
  1372. if not cls._meta.swapped:
  1373. databases = kwargs.get("databases") or []
  1374. errors += [
  1375. *cls._check_fields(**kwargs),
  1376. *cls._check_m2m_through_same_relationship(),
  1377. *cls._check_long_column_names(databases),
  1378. ]
  1379. clash_errors = (
  1380. *cls._check_id_field(),
  1381. *cls._check_field_name_clashes(),
  1382. *cls._check_model_name_db_lookup_clashes(),
  1383. *cls._check_property_name_related_field_accessor_clashes(),
  1384. *cls._check_single_primary_key(),
  1385. )
  1386. errors.extend(clash_errors)
  1387. # If there are field name clashes, hide consequent column name
  1388. # clashes.
  1389. if not clash_errors:
  1390. errors.extend(cls._check_column_name_clashes())
  1391. errors += [
  1392. *cls._check_index_together(),
  1393. *cls._check_unique_together(),
  1394. *cls._check_indexes(databases),
  1395. *cls._check_ordering(),
  1396. *cls._check_constraints(databases),
  1397. *cls._check_default_pk(),
  1398. *cls._check_db_table_comment(databases),
  1399. ]
  1400. return errors
  1401. @classmethod
  1402. def _check_default_pk(cls):
  1403. if (
  1404. not cls._meta.abstract
  1405. and cls._meta.pk.auto_created
  1406. and
  1407. # Inherited PKs are checked in parents models.
  1408. not (
  1409. isinstance(cls._meta.pk, OneToOneField)
  1410. and cls._meta.pk.remote_field.parent_link
  1411. )
  1412. and not settings.is_overridden("DEFAULT_AUTO_FIELD")
  1413. and cls._meta.app_config
  1414. and not cls._meta.app_config._is_default_auto_field_overridden
  1415. ):
  1416. return [
  1417. checks.Warning(
  1418. f"Auto-created primary key used when not defining a "
  1419. f"primary key type, by default "
  1420. f"'{settings.DEFAULT_AUTO_FIELD}'.",
  1421. hint=(
  1422. f"Configure the DEFAULT_AUTO_FIELD setting or the "
  1423. f"{cls._meta.app_config.__class__.__qualname__}."
  1424. f"default_auto_field attribute to point to a subclass "
  1425. f"of AutoField, e.g. 'django.db.models.BigAutoField'."
  1426. ),
  1427. obj=cls,
  1428. id="models.W042",
  1429. ),
  1430. ]
  1431. return []
  1432. @classmethod
  1433. def _check_db_table_comment(cls, databases):
  1434. if not cls._meta.db_table_comment:
  1435. return []
  1436. errors = []
  1437. for db in databases:
  1438. if not router.allow_migrate_model(db, cls):
  1439. continue
  1440. connection = connections[db]
  1441. if not (
  1442. connection.features.supports_comments
  1443. or "supports_comments" in cls._meta.required_db_features
  1444. ):
  1445. errors.append(
  1446. checks.Warning(
  1447. f"{connection.display_name} does not support comments on "
  1448. f"tables (db_table_comment).",
  1449. obj=cls,
  1450. id="models.W046",
  1451. )
  1452. )
  1453. return errors
  1454. @classmethod
  1455. def _check_swappable(cls):
  1456. """Check if the swapped model exists."""
  1457. errors = []
  1458. if cls._meta.swapped:
  1459. try:
  1460. apps.get_model(cls._meta.swapped)
  1461. except ValueError:
  1462. errors.append(
  1463. checks.Error(
  1464. "'%s' is not of the form 'app_label.app_name'."
  1465. % cls._meta.swappable,
  1466. id="models.E001",
  1467. )
  1468. )
  1469. except LookupError:
  1470. app_label, model_name = cls._meta.swapped.split(".")
  1471. errors.append(
  1472. checks.Error(
  1473. "'%s' references '%s.%s', which has not been "
  1474. "installed, or is abstract."
  1475. % (cls._meta.swappable, app_label, model_name),
  1476. id="models.E002",
  1477. )
  1478. )
  1479. return errors
  1480. @classmethod
  1481. def _check_model(cls):
  1482. errors = []
  1483. if cls._meta.proxy:
  1484. if cls._meta.local_fields or cls._meta.local_many_to_many:
  1485. errors.append(
  1486. checks.Error(
  1487. "Proxy model '%s' contains model fields." % cls.__name__,
  1488. id="models.E017",
  1489. )
  1490. )
  1491. return errors
  1492. @classmethod
  1493. def _check_managers(cls, **kwargs):
  1494. """Perform all manager checks."""
  1495. errors = []
  1496. for manager in cls._meta.managers:
  1497. errors.extend(manager.check(**kwargs))
  1498. return errors
  1499. @classmethod
  1500. def _check_fields(cls, **kwargs):
  1501. """Perform all field checks."""
  1502. errors = []
  1503. for field in cls._meta.local_fields:
  1504. errors.extend(field.check(**kwargs))
  1505. for field in cls._meta.local_many_to_many:
  1506. errors.extend(field.check(from_model=cls, **kwargs))
  1507. return errors
  1508. @classmethod
  1509. def _check_m2m_through_same_relationship(cls):
  1510. """Check if no relationship model is used by more than one m2m field."""
  1511. errors = []
  1512. seen_intermediary_signatures = []
  1513. fields = cls._meta.local_many_to_many
  1514. # Skip when the target model wasn't found.
  1515. fields = (f for f in fields if isinstance(f.remote_field.model, ModelBase))
  1516. # Skip when the relationship model wasn't found.
  1517. fields = (f for f in fields if isinstance(f.remote_field.through, ModelBase))
  1518. for f in fields:
  1519. signature = (
  1520. f.remote_field.model,
  1521. cls,
  1522. f.remote_field.through,
  1523. f.remote_field.through_fields,
  1524. )
  1525. if signature in seen_intermediary_signatures:
  1526. errors.append(
  1527. checks.Error(
  1528. "The model has two identical many-to-many relations "
  1529. "through the intermediate model '%s'."
  1530. % f.remote_field.through._meta.label,
  1531. obj=cls,
  1532. id="models.E003",
  1533. )
  1534. )
  1535. else:
  1536. seen_intermediary_signatures.append(signature)
  1537. return errors
  1538. @classmethod
  1539. def _check_id_field(cls):
  1540. """Check if `id` field is a primary key."""
  1541. fields = [
  1542. f for f in cls._meta.local_fields if f.name == "id" and f != cls._meta.pk
  1543. ]
  1544. # fields is empty or consists of the invalid "id" field
  1545. if fields and not fields[0].primary_key and cls._meta.pk.name == "id":
  1546. return [
  1547. checks.Error(
  1548. "'id' can only be used as a field name if the field also "
  1549. "sets 'primary_key=True'.",
  1550. obj=cls,
  1551. id="models.E004",
  1552. )
  1553. ]
  1554. else:
  1555. return []
  1556. @classmethod
  1557. def _check_field_name_clashes(cls):
  1558. """Forbid field shadowing in multi-table inheritance."""
  1559. errors = []
  1560. used_fields = {} # name or attname -> field
  1561. # Check that multi-inheritance doesn't cause field name shadowing.
  1562. for parent in cls._meta.get_parent_list():
  1563. for f in parent._meta.local_fields:
  1564. clash = used_fields.get(f.name) or used_fields.get(f.attname) or None
  1565. if clash:
  1566. errors.append(
  1567. checks.Error(
  1568. "The field '%s' from parent model "
  1569. "'%s' clashes with the field '%s' "
  1570. "from parent model '%s'."
  1571. % (clash.name, clash.model._meta, f.name, f.model._meta),
  1572. obj=cls,
  1573. id="models.E005",
  1574. )
  1575. )
  1576. used_fields[f.name] = f
  1577. used_fields[f.attname] = f
  1578. # Check that fields defined in the model don't clash with fields from
  1579. # parents, including auto-generated fields like multi-table inheritance
  1580. # child accessors.
  1581. for parent in cls._meta.get_parent_list():
  1582. for f in parent._meta.get_fields():
  1583. if f not in used_fields:
  1584. used_fields[f.name] = f
  1585. for f in cls._meta.local_fields:
  1586. clash = used_fields.get(f.name) or used_fields.get(f.attname) or None
  1587. # Note that we may detect clash between user-defined non-unique
  1588. # field "id" and automatically added unique field "id", both
  1589. # defined at the same model. This special case is considered in
  1590. # _check_id_field and here we ignore it.
  1591. id_conflict = (
  1592. f.name == "id" and clash and clash.name == "id" and clash.model == cls
  1593. )
  1594. if clash and not id_conflict:
  1595. errors.append(
  1596. checks.Error(
  1597. "The field '%s' clashes with the field '%s' "
  1598. "from model '%s'." % (f.name, clash.name, clash.model._meta),
  1599. obj=f,
  1600. id="models.E006",
  1601. )
  1602. )
  1603. used_fields[f.name] = f
  1604. used_fields[f.attname] = f
  1605. return errors
  1606. @classmethod
  1607. def _check_column_name_clashes(cls):
  1608. # Store a list of column names which have already been used by other fields.
  1609. used_column_names = []
  1610. errors = []
  1611. for f in cls._meta.local_fields:
  1612. _, column_name = f.get_attname_column()
  1613. # Ensure the column name is not already in use.
  1614. if column_name and column_name in used_column_names:
  1615. errors.append(
  1616. checks.Error(
  1617. "Field '%s' has column name '%s' that is used by "
  1618. "another field." % (f.name, column_name),
  1619. hint="Specify a 'db_column' for the field.",
  1620. obj=cls,
  1621. id="models.E007",
  1622. )
  1623. )
  1624. else:
  1625. used_column_names.append(column_name)
  1626. return errors
  1627. @classmethod
  1628. def _check_model_name_db_lookup_clashes(cls):
  1629. errors = []
  1630. model_name = cls.__name__
  1631. if model_name.startswith("_") or model_name.endswith("_"):
  1632. errors.append(
  1633. checks.Error(
  1634. "The model name '%s' cannot start or end with an underscore "
  1635. "as it collides with the query lookup syntax." % model_name,
  1636. obj=cls,
  1637. id="models.E023",
  1638. )
  1639. )
  1640. elif LOOKUP_SEP in model_name:
  1641. errors.append(
  1642. checks.Error(
  1643. "The model name '%s' cannot contain double underscores as "
  1644. "it collides with the query lookup syntax." % model_name,
  1645. obj=cls,
  1646. id="models.E024",
  1647. )
  1648. )
  1649. return errors
  1650. @classmethod
  1651. def _check_property_name_related_field_accessor_clashes(cls):
  1652. errors = []
  1653. property_names = cls._meta._property_names
  1654. related_field_accessors = (
  1655. f.get_attname()
  1656. for f in cls._meta._get_fields(reverse=False)
  1657. if f.is_relation and f.related_model is not None
  1658. )
  1659. for accessor in related_field_accessors:
  1660. if accessor in property_names:
  1661. errors.append(
  1662. checks.Error(
  1663. "The property '%s' clashes with a related field "
  1664. "accessor." % accessor,
  1665. obj=cls,
  1666. id="models.E025",
  1667. )
  1668. )
  1669. return errors
  1670. @classmethod
  1671. def _check_single_primary_key(cls):
  1672. errors = []
  1673. if sum(1 for f in cls._meta.local_fields if f.primary_key) > 1:
  1674. errors.append(
  1675. checks.Error(
  1676. "The model cannot have more than one field with "
  1677. "'primary_key=True'.",
  1678. obj=cls,
  1679. id="models.E026",
  1680. )
  1681. )
  1682. return errors
  1683. # RemovedInDjango51Warning.
  1684. @classmethod
  1685. def _check_index_together(cls):
  1686. """Check the value of "index_together" option."""
  1687. if not isinstance(cls._meta.index_together, (tuple, list)):
  1688. return [
  1689. checks.Error(
  1690. "'index_together' must be a list or tuple.",
  1691. obj=cls,
  1692. id="models.E008",
  1693. )
  1694. ]
  1695. elif any(
  1696. not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together
  1697. ):
  1698. return [
  1699. checks.Error(
  1700. "All 'index_together' elements must be lists or tuples.",
  1701. obj=cls,
  1702. id="models.E009",
  1703. )
  1704. ]
  1705. else:
  1706. errors = []
  1707. for fields in cls._meta.index_together:
  1708. errors.extend(cls._check_local_fields(fields, "index_together"))
  1709. return errors
  1710. @classmethod
  1711. def _check_unique_together(cls):
  1712. """Check the value of "unique_together" option."""
  1713. if not isinstance(cls._meta.unique_together, (tuple, list)):
  1714. return [
  1715. checks.Error(
  1716. "'unique_together' must be a list or tuple.",
  1717. obj=cls,
  1718. id="models.E010",
  1719. )
  1720. ]
  1721. elif any(
  1722. not isinstance(fields, (tuple, list))
  1723. for fields in cls._meta.unique_together
  1724. ):
  1725. return [
  1726. checks.Error(
  1727. "All 'unique_together' elements must be lists or tuples.",
  1728. obj=cls,
  1729. id="models.E011",
  1730. )
  1731. ]
  1732. else:
  1733. errors = []
  1734. for fields in cls._meta.unique_together:
  1735. errors.extend(cls._check_local_fields(fields, "unique_together"))
  1736. return errors
  1737. @classmethod
  1738. def _check_indexes(cls, databases):
  1739. """Check fields, names, and conditions of indexes."""
  1740. errors = []
  1741. references = set()
  1742. for index in cls._meta.indexes:
  1743. # Index name can't start with an underscore or a number, restricted
  1744. # for cross-database compatibility with Oracle.
  1745. if index.name[0] == "_" or index.name[0].isdigit():
  1746. errors.append(
  1747. checks.Error(
  1748. "The index name '%s' cannot start with an underscore "
  1749. "or a number." % index.name,
  1750. obj=cls,
  1751. id="models.E033",
  1752. ),
  1753. )
  1754. if len(index.name) > index.max_name_length:
  1755. errors.append(
  1756. checks.Error(
  1757. "The index name '%s' cannot be longer than %d "
  1758. "characters." % (index.name, index.max_name_length),
  1759. obj=cls,
  1760. id="models.E034",
  1761. ),
  1762. )
  1763. if index.contains_expressions:
  1764. for expression in index.expressions:
  1765. references.update(
  1766. ref[0] for ref in cls._get_expr_references(expression)
  1767. )
  1768. for db in databases:
  1769. if not router.allow_migrate_model(db, cls):
  1770. continue
  1771. connection = connections[db]
  1772. if not (
  1773. connection.features.supports_partial_indexes
  1774. or "supports_partial_indexes" in cls._meta.required_db_features
  1775. ) and any(index.condition is not None for index in cls._meta.indexes):
  1776. errors.append(
  1777. checks.Warning(
  1778. "%s does not support indexes with conditions."
  1779. % connection.display_name,
  1780. hint=(
  1781. "Conditions will be ignored. Silence this warning "
  1782. "if you don't care about it."
  1783. ),
  1784. obj=cls,
  1785. id="models.W037",
  1786. )
  1787. )
  1788. if not (
  1789. connection.features.supports_covering_indexes
  1790. or "supports_covering_indexes" in cls._meta.required_db_features
  1791. ) and any(index.include for index in cls._meta.indexes):
  1792. errors.append(
  1793. checks.Warning(
  1794. "%s does not support indexes with non-key columns."
  1795. % connection.display_name,
  1796. hint=(
  1797. "Non-key columns will be ignored. Silence this "
  1798. "warning if you don't care about it."
  1799. ),
  1800. obj=cls,
  1801. id="models.W040",
  1802. )
  1803. )
  1804. if not (
  1805. connection.features.supports_expression_indexes
  1806. or "supports_expression_indexes" in cls._meta.required_db_features
  1807. ) and any(index.contains_expressions for index in cls._meta.indexes):
  1808. errors.append(
  1809. checks.Warning(
  1810. "%s does not support indexes on expressions."
  1811. % connection.display_name,
  1812. hint=(
  1813. "An index won't be created. Silence this warning "
  1814. "if you don't care about it."
  1815. ),
  1816. obj=cls,
  1817. id="models.W043",
  1818. )
  1819. )
  1820. fields = [
  1821. field for index in cls._meta.indexes for field, _ in index.fields_orders
  1822. ]
  1823. fields += [include for index in cls._meta.indexes for include in index.include]
  1824. fields += references
  1825. errors.extend(cls._check_local_fields(fields, "indexes"))
  1826. return errors
  1827. @classmethod
  1828. def _check_local_fields(cls, fields, option):
  1829. from django.db import models
  1830. # In order to avoid hitting the relation tree prematurely, we use our
  1831. # own fields_map instead of using get_field()
  1832. forward_fields_map = {}
  1833. for field in cls._meta._get_fields(reverse=False):
  1834. forward_fields_map[field.name] = field
  1835. if hasattr(field, "attname"):
  1836. forward_fields_map[field.attname] = field
  1837. errors = []
  1838. for field_name in fields:
  1839. try:
  1840. field = forward_fields_map[field_name]
  1841. except KeyError:
  1842. errors.append(
  1843. checks.Error(
  1844. "'%s' refers to the nonexistent field '%s'."
  1845. % (
  1846. option,
  1847. field_name,
  1848. ),
  1849. obj=cls,
  1850. id="models.E012",
  1851. )
  1852. )
  1853. else:
  1854. if isinstance(field.remote_field, models.ManyToManyRel):
  1855. errors.append(
  1856. checks.Error(
  1857. "'%s' refers to a ManyToManyField '%s', but "
  1858. "ManyToManyFields are not permitted in '%s'."
  1859. % (
  1860. option,
  1861. field_name,
  1862. option,
  1863. ),
  1864. obj=cls,
  1865. id="models.E013",
  1866. )
  1867. )
  1868. elif field not in cls._meta.local_fields:
  1869. errors.append(
  1870. checks.Error(
  1871. "'%s' refers to field '%s' which is not local to model "
  1872. "'%s'." % (option, field_name, cls._meta.object_name),
  1873. hint="This issue may be caused by multi-table inheritance.",
  1874. obj=cls,
  1875. id="models.E016",
  1876. )
  1877. )
  1878. return errors
  1879. @classmethod
  1880. def _check_ordering(cls):
  1881. """
  1882. Check "ordering" option -- is it a list of strings and do all fields
  1883. exist?
  1884. """
  1885. if cls._meta._ordering_clash:
  1886. return [
  1887. checks.Error(
  1888. "'ordering' and 'order_with_respect_to' cannot be used together.",
  1889. obj=cls,
  1890. id="models.E021",
  1891. ),
  1892. ]
  1893. if cls._meta.order_with_respect_to or not cls._meta.ordering:
  1894. return []
  1895. if not isinstance(cls._meta.ordering, (list, tuple)):
  1896. return [
  1897. checks.Error(
  1898. "'ordering' must be a tuple or list (even if you want to order by "
  1899. "only one field).",
  1900. obj=cls,
  1901. id="models.E014",
  1902. )
  1903. ]
  1904. errors = []
  1905. fields = cls._meta.ordering
  1906. # Skip expressions and '?' fields.
  1907. fields = (f for f in fields if isinstance(f, str) and f != "?")
  1908. # Convert "-field" to "field".
  1909. fields = ((f[1:] if f.startswith("-") else f) for f in fields)
  1910. # Separate related fields and non-related fields.
  1911. _fields = []
  1912. related_fields = []
  1913. for f in fields:
  1914. if LOOKUP_SEP in f:
  1915. related_fields.append(f)
  1916. else:
  1917. _fields.append(f)
  1918. fields = _fields
  1919. # Check related fields.
  1920. for field in related_fields:
  1921. _cls = cls
  1922. fld = None
  1923. for part in field.split(LOOKUP_SEP):
  1924. try:
  1925. # pk is an alias that won't be found by opts.get_field.
  1926. if part == "pk":
  1927. fld = _cls._meta.pk
  1928. else:
  1929. fld = _cls._meta.get_field(part)
  1930. if fld.is_relation:
  1931. _cls = fld.path_infos[-1].to_opts.model
  1932. else:
  1933. _cls = None
  1934. except (FieldDoesNotExist, AttributeError):
  1935. if fld is None or (
  1936. fld.get_transform(part) is None and fld.get_lookup(part) is None
  1937. ):
  1938. errors.append(
  1939. checks.Error(
  1940. "'ordering' refers to the nonexistent field, "
  1941. "related field, or lookup '%s'." % field,
  1942. obj=cls,
  1943. id="models.E015",
  1944. )
  1945. )
  1946. # Skip ordering on pk. This is always a valid order_by field
  1947. # but is an alias and therefore won't be found by opts.get_field.
  1948. fields = {f for f in fields if f != "pk"}
  1949. # Check for invalid or nonexistent fields in ordering.
  1950. invalid_fields = []
  1951. # Any field name that is not present in field_names does not exist.
  1952. # Also, ordering by m2m fields is not allowed.
  1953. opts = cls._meta
  1954. valid_fields = set(
  1955. chain.from_iterable(
  1956. (f.name, f.attname)
  1957. if not (f.auto_created and not f.concrete)
  1958. else (f.field.related_query_name(),)
  1959. for f in chain(opts.fields, opts.related_objects)
  1960. )
  1961. )
  1962. invalid_fields.extend(fields - valid_fields)
  1963. for invalid_field in invalid_fields:
  1964. errors.append(
  1965. checks.Error(
  1966. "'ordering' refers to the nonexistent field, related "
  1967. "field, or lookup '%s'." % invalid_field,
  1968. obj=cls,
  1969. id="models.E015",
  1970. )
  1971. )
  1972. return errors
  1973. @classmethod
  1974. def _check_long_column_names(cls, databases):
  1975. """
  1976. Check that any auto-generated column names are shorter than the limits
  1977. for each database in which the model will be created.
  1978. """
  1979. if not databases:
  1980. return []
  1981. errors = []
  1982. allowed_len = None
  1983. db_alias = None
  1984. # Find the minimum max allowed length among all specified db_aliases.
  1985. for db in databases:
  1986. # skip databases where the model won't be created
  1987. if not router.allow_migrate_model(db, cls):
  1988. continue
  1989. connection = connections[db]
  1990. max_name_length = connection.ops.max_name_length()
  1991. if max_name_length is None or connection.features.truncates_names:
  1992. continue
  1993. else:
  1994. if allowed_len is None:
  1995. allowed_len = max_name_length
  1996. db_alias = db
  1997. elif max_name_length < allowed_len:
  1998. allowed_len = max_name_length
  1999. db_alias = db
  2000. if allowed_len is None:
  2001. return errors
  2002. for f in cls._meta.local_fields:
  2003. _, column_name = f.get_attname_column()
  2004. # Check if auto-generated name for the field is too long
  2005. # for the database.
  2006. if (
  2007. f.db_column is None
  2008. and column_name is not None
  2009. and len(column_name) > allowed_len
  2010. ):
  2011. errors.append(
  2012. checks.Error(
  2013. 'Autogenerated column name too long for field "%s". '
  2014. 'Maximum length is "%s" for database "%s".'
  2015. % (column_name, allowed_len, db_alias),
  2016. hint="Set the column name manually using 'db_column'.",
  2017. obj=cls,
  2018. id="models.E018",
  2019. )
  2020. )
  2021. for f in cls._meta.local_many_to_many:
  2022. # Skip nonexistent models.
  2023. if isinstance(f.remote_field.through, str):
  2024. continue
  2025. # Check if auto-generated name for the M2M field is too long
  2026. # for the database.
  2027. for m2m in f.remote_field.through._meta.local_fields:
  2028. _, rel_name = m2m.get_attname_column()
  2029. if (
  2030. m2m.db_column is None
  2031. and rel_name is not None
  2032. and len(rel_name) > allowed_len
  2033. ):
  2034. errors.append(
  2035. checks.Error(
  2036. "Autogenerated column name too long for M2M field "
  2037. '"%s". Maximum length is "%s" for database "%s".'
  2038. % (rel_name, allowed_len, db_alias),
  2039. hint=(
  2040. "Use 'through' to create a separate model for "
  2041. "M2M and then set column_name using 'db_column'."
  2042. ),
  2043. obj=cls,
  2044. id="models.E019",
  2045. )
  2046. )
  2047. return errors
  2048. @classmethod
  2049. def _get_expr_references(cls, expr):
  2050. if isinstance(expr, Q):
  2051. for child in expr.children:
  2052. if isinstance(child, tuple):
  2053. lookup, value = child
  2054. yield tuple(lookup.split(LOOKUP_SEP))
  2055. yield from cls._get_expr_references(value)
  2056. else:
  2057. yield from cls._get_expr_references(child)
  2058. elif isinstance(expr, F):
  2059. yield tuple(expr.name.split(LOOKUP_SEP))
  2060. elif hasattr(expr, "get_source_expressions"):
  2061. for src_expr in expr.get_source_expressions():
  2062. yield from cls._get_expr_references(src_expr)
  2063. @classmethod
  2064. def _check_constraints(cls, databases):
  2065. errors = []
  2066. for db in databases:
  2067. if not router.allow_migrate_model(db, cls):
  2068. continue
  2069. connection = connections[db]
  2070. if not (
  2071. connection.features.supports_table_check_constraints
  2072. or "supports_table_check_constraints" in cls._meta.required_db_features
  2073. ) and any(
  2074. isinstance(constraint, CheckConstraint)
  2075. for constraint in cls._meta.constraints
  2076. ):
  2077. errors.append(
  2078. checks.Warning(
  2079. "%s does not support check constraints."
  2080. % connection.display_name,
  2081. hint=(
  2082. "A constraint won't be created. Silence this "
  2083. "warning if you don't care about it."
  2084. ),
  2085. obj=cls,
  2086. id="models.W027",
  2087. )
  2088. )
  2089. if not (
  2090. connection.features.supports_partial_indexes
  2091. or "supports_partial_indexes" in cls._meta.required_db_features
  2092. ) and any(
  2093. isinstance(constraint, UniqueConstraint)
  2094. and constraint.condition is not None
  2095. for constraint in cls._meta.constraints
  2096. ):
  2097. errors.append(
  2098. checks.Warning(
  2099. "%s does not support unique constraints with "
  2100. "conditions." % connection.display_name,
  2101. hint=(
  2102. "A constraint won't be created. Silence this "
  2103. "warning if you don't care about it."
  2104. ),
  2105. obj=cls,
  2106. id="models.W036",
  2107. )
  2108. )
  2109. if not (
  2110. connection.features.supports_deferrable_unique_constraints
  2111. or "supports_deferrable_unique_constraints"
  2112. in cls._meta.required_db_features
  2113. ) and any(
  2114. isinstance(constraint, UniqueConstraint)
  2115. and constraint.deferrable is not None
  2116. for constraint in cls._meta.constraints
  2117. ):
  2118. errors.append(
  2119. checks.Warning(
  2120. "%s does not support deferrable unique constraints."
  2121. % connection.display_name,
  2122. hint=(
  2123. "A constraint won't be created. Silence this "
  2124. "warning if you don't care about it."
  2125. ),
  2126. obj=cls,
  2127. id="models.W038",
  2128. )
  2129. )
  2130. if not (
  2131. connection.features.supports_covering_indexes
  2132. or "supports_covering_indexes" in cls._meta.required_db_features
  2133. ) and any(
  2134. isinstance(constraint, UniqueConstraint) and constraint.include
  2135. for constraint in cls._meta.constraints
  2136. ):
  2137. errors.append(
  2138. checks.Warning(
  2139. "%s does not support unique constraints with non-key "
  2140. "columns." % connection.display_name,
  2141. hint=(
  2142. "A constraint won't be created. Silence this "
  2143. "warning if you don't care about it."
  2144. ),
  2145. obj=cls,
  2146. id="models.W039",
  2147. )
  2148. )
  2149. if not (
  2150. connection.features.supports_expression_indexes
  2151. or "supports_expression_indexes" in cls._meta.required_db_features
  2152. ) and any(
  2153. isinstance(constraint, UniqueConstraint)
  2154. and constraint.contains_expressions
  2155. for constraint in cls._meta.constraints
  2156. ):
  2157. errors.append(
  2158. checks.Warning(
  2159. "%s does not support unique constraints on "
  2160. "expressions." % connection.display_name,
  2161. hint=(
  2162. "A constraint won't be created. Silence this "
  2163. "warning if you don't care about it."
  2164. ),
  2165. obj=cls,
  2166. id="models.W044",
  2167. )
  2168. )
  2169. fields = set(
  2170. chain.from_iterable(
  2171. (*constraint.fields, *constraint.include)
  2172. for constraint in cls._meta.constraints
  2173. if isinstance(constraint, UniqueConstraint)
  2174. )
  2175. )
  2176. references = set()
  2177. for constraint in cls._meta.constraints:
  2178. if isinstance(constraint, UniqueConstraint):
  2179. if (
  2180. connection.features.supports_partial_indexes
  2181. or "supports_partial_indexes"
  2182. not in cls._meta.required_db_features
  2183. ) and isinstance(constraint.condition, Q):
  2184. references.update(
  2185. cls._get_expr_references(constraint.condition)
  2186. )
  2187. if (
  2188. connection.features.supports_expression_indexes
  2189. or "supports_expression_indexes"
  2190. not in cls._meta.required_db_features
  2191. ) and constraint.contains_expressions:
  2192. for expression in constraint.expressions:
  2193. references.update(cls._get_expr_references(expression))
  2194. elif isinstance(constraint, CheckConstraint):
  2195. if (
  2196. connection.features.supports_table_check_constraints
  2197. or "supports_table_check_constraints"
  2198. not in cls._meta.required_db_features
  2199. ):
  2200. if isinstance(constraint.check, Q):
  2201. references.update(
  2202. cls._get_expr_references(constraint.check)
  2203. )
  2204. if any(
  2205. isinstance(expr, RawSQL)
  2206. for expr in constraint.check.flatten()
  2207. ):
  2208. errors.append(
  2209. checks.Warning(
  2210. f"Check constraint {constraint.name!r} contains "
  2211. f"RawSQL() expression and won't be validated "
  2212. f"during the model full_clean().",
  2213. hint=(
  2214. "Silence this warning if you don't care about "
  2215. "it."
  2216. ),
  2217. obj=cls,
  2218. id="models.W045",
  2219. ),
  2220. )
  2221. for field_name, *lookups in references:
  2222. # pk is an alias that won't be found by opts.get_field.
  2223. if field_name != "pk":
  2224. fields.add(field_name)
  2225. if not lookups:
  2226. # If it has no lookups it cannot result in a JOIN.
  2227. continue
  2228. try:
  2229. if field_name == "pk":
  2230. field = cls._meta.pk
  2231. else:
  2232. field = cls._meta.get_field(field_name)
  2233. if not field.is_relation or field.many_to_many or field.one_to_many:
  2234. continue
  2235. except FieldDoesNotExist:
  2236. continue
  2237. # JOIN must happen at the first lookup.
  2238. first_lookup = lookups[0]
  2239. if (
  2240. hasattr(field, "get_transform")
  2241. and hasattr(field, "get_lookup")
  2242. and field.get_transform(first_lookup) is None
  2243. and field.get_lookup(first_lookup) is None
  2244. ):
  2245. errors.append(
  2246. checks.Error(
  2247. "'constraints' refers to the joined field '%s'."
  2248. % LOOKUP_SEP.join([field_name] + lookups),
  2249. obj=cls,
  2250. id="models.E041",
  2251. )
  2252. )
  2253. errors.extend(cls._check_local_fields(fields, "constraints"))
  2254. return errors
  2255. ############################################
  2256. # HELPER FUNCTIONS (CURRIED MODEL METHODS) #
  2257. ############################################
  2258. # ORDERING METHODS #########################
  2259. def method_set_order(self, ordered_obj, id_list, using=None):
  2260. order_wrt = ordered_obj._meta.order_with_respect_to
  2261. filter_args = order_wrt.get_forward_related_filter(self)
  2262. ordered_obj.objects.db_manager(using).filter(**filter_args).bulk_update(
  2263. [ordered_obj(pk=pk, _order=order) for order, pk in enumerate(id_list)],
  2264. ["_order"],
  2265. )
  2266. def method_get_order(self, ordered_obj):
  2267. order_wrt = ordered_obj._meta.order_with_respect_to
  2268. filter_args = order_wrt.get_forward_related_filter(self)
  2269. pk_name = ordered_obj._meta.pk.name
  2270. return ordered_obj.objects.filter(**filter_args).values_list(pk_name, flat=True)
  2271. def make_foreign_order_accessors(model, related_model):
  2272. setattr(
  2273. related_model,
  2274. "get_%s_order" % model.__name__.lower(),
  2275. partialmethod(method_get_order, model),
  2276. )
  2277. setattr(
  2278. related_model,
  2279. "set_%s_order" % model.__name__.lower(),
  2280. partialmethod(method_set_order, model),
  2281. )
  2282. ########
  2283. # MISC #
  2284. ########
  2285. def model_unpickle(model_id):
  2286. """Used to unpickle Model subclasses with deferred fields."""
  2287. if isinstance(model_id, tuple):
  2288. model = apps.get_model(*model_id)
  2289. else:
  2290. # Backwards compat - the model was cached directly in earlier versions.
  2291. model = model_id
  2292. return model.__new__(model)
  2293. model_unpickle.__safe_for_unpickle__ = True