base.py 95 KB

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