base.py 97 KB

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