Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.py 96KB

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