__init__.py 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872
  1. import copy
  2. import datetime
  3. import decimal
  4. import operator
  5. import uuid
  6. import warnings
  7. from base64 import b64decode, b64encode
  8. from functools import partialmethod, total_ordering
  9. from django import forms
  10. from django.apps import apps
  11. from django.conf import settings
  12. from django.core import checks, exceptions, validators
  13. from django.db import connection, connections, router
  14. from django.db.models.constants import LOOKUP_SEP
  15. from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin
  16. from django.utils import timezone
  17. from django.utils.choices import (
  18. BlankChoiceIterator,
  19. CallableChoiceIterator,
  20. flatten_choices,
  21. normalize_choices,
  22. )
  23. from django.utils.datastructures import DictWrapper
  24. from django.utils.dateparse import (
  25. parse_date,
  26. parse_datetime,
  27. parse_duration,
  28. parse_time,
  29. )
  30. from django.utils.duration import duration_microseconds, duration_string
  31. from django.utils.functional import Promise, cached_property
  32. from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_ipv6_address
  33. from django.utils.itercompat import is_iterable
  34. from django.utils.text import capfirst
  35. from django.utils.translation import gettext_lazy as _
  36. __all__ = [
  37. "AutoField",
  38. "BLANK_CHOICE_DASH",
  39. "BigAutoField",
  40. "BigIntegerField",
  41. "BinaryField",
  42. "BooleanField",
  43. "CharField",
  44. "CommaSeparatedIntegerField",
  45. "DateField",
  46. "DateTimeField",
  47. "DecimalField",
  48. "DurationField",
  49. "EmailField",
  50. "Empty",
  51. "Field",
  52. "FilePathField",
  53. "FloatField",
  54. "GenericIPAddressField",
  55. "IPAddressField",
  56. "IntegerField",
  57. "NOT_PROVIDED",
  58. "NullBooleanField",
  59. "PositiveBigIntegerField",
  60. "PositiveIntegerField",
  61. "PositiveSmallIntegerField",
  62. "SlugField",
  63. "SmallAutoField",
  64. "SmallIntegerField",
  65. "TextField",
  66. "TimeField",
  67. "URLField",
  68. "UUIDField",
  69. ]
  70. class Empty:
  71. pass
  72. class NOT_PROVIDED:
  73. pass
  74. # The values to use for "blank" in SelectFields. Will be appended to the start
  75. # of most "choices" lists.
  76. BLANK_CHOICE_DASH = [("", "---------")]
  77. def _load_field(app_label, model_name, field_name):
  78. return apps.get_model(app_label, model_name)._meta.get_field(field_name)
  79. # A guide to Field parameters:
  80. #
  81. # * name: The name of the field specified in the model.
  82. # * attname: The attribute to use on the model object. This is the same as
  83. # "name", except in the case of ForeignKeys, where "_id" is
  84. # appended.
  85. # * db_column: The db_column specified in the model (or None).
  86. # * column: The database column for this field. This is the same as
  87. # "attname", except if db_column is specified.
  88. #
  89. # Code that introspects values, or does other dynamic things, should use
  90. # attname. For example, this gets the primary key value of object "obj":
  91. #
  92. # getattr(obj, opts.pk.attname)
  93. def _empty(of_cls):
  94. new = Empty()
  95. new.__class__ = of_cls
  96. return new
  97. def return_None():
  98. return None
  99. @total_ordering
  100. class Field(RegisterLookupMixin):
  101. """Base class for all field types"""
  102. # Designates whether empty strings fundamentally are allowed at the
  103. # database level.
  104. empty_strings_allowed = True
  105. empty_values = list(validators.EMPTY_VALUES)
  106. # These track each time a Field instance is created. Used to retain order.
  107. # The auto_creation_counter is used for fields that Django implicitly
  108. # creates, creation_counter is used for all user-specified fields.
  109. creation_counter = 0
  110. auto_creation_counter = -1
  111. default_validators = [] # Default set of validators
  112. default_error_messages = {
  113. "invalid_choice": _("Value %(value)r is not a valid choice."),
  114. "null": _("This field cannot be null."),
  115. "blank": _("This field cannot be blank."),
  116. "unique": _("%(model_name)s with this %(field_label)s already exists."),
  117. "unique_for_date": _(
  118. # Translators: The 'lookup_type' is one of 'date', 'year' or
  119. # 'month'. Eg: "Title must be unique for pub_date year"
  120. "%(field_label)s must be unique for "
  121. "%(date_field_label)s %(lookup_type)s."
  122. ),
  123. }
  124. system_check_deprecated_details = None
  125. system_check_removed_details = None
  126. # Attributes that don't affect a column definition.
  127. # These attributes are ignored when altering the field.
  128. non_db_attrs = (
  129. "blank",
  130. "choices",
  131. "db_column",
  132. "editable",
  133. "error_messages",
  134. "help_text",
  135. "limit_choices_to",
  136. # Database-level options are not supported, see #21961.
  137. "on_delete",
  138. "related_name",
  139. "related_query_name",
  140. "validators",
  141. "verbose_name",
  142. )
  143. # Field flags
  144. hidden = False
  145. many_to_many = None
  146. many_to_one = None
  147. one_to_many = None
  148. one_to_one = None
  149. related_model = None
  150. generated = False
  151. descriptor_class = DeferredAttribute
  152. # Generic field type description, usually overridden by subclasses
  153. def _description(self):
  154. return _("Field of type: %(field_type)s") % {
  155. "field_type": self.__class__.__name__
  156. }
  157. description = property(_description)
  158. def __init__(
  159. self,
  160. verbose_name=None,
  161. name=None,
  162. primary_key=False,
  163. max_length=None,
  164. unique=False,
  165. blank=False,
  166. null=False,
  167. db_index=False,
  168. rel=None,
  169. default=NOT_PROVIDED,
  170. editable=True,
  171. serialize=True,
  172. unique_for_date=None,
  173. unique_for_month=None,
  174. unique_for_year=None,
  175. choices=None,
  176. help_text="",
  177. db_column=None,
  178. db_tablespace=None,
  179. auto_created=False,
  180. validators=(),
  181. error_messages=None,
  182. db_comment=None,
  183. db_default=NOT_PROVIDED,
  184. ):
  185. self.name = name
  186. self.verbose_name = verbose_name # May be set by set_attributes_from_name
  187. self._verbose_name = verbose_name # Store original for deconstruction
  188. self.primary_key = primary_key
  189. self.max_length, self._unique = max_length, unique
  190. self.blank, self.null = blank, null
  191. self.remote_field = rel
  192. self.is_relation = self.remote_field is not None
  193. self.default = default
  194. self.db_default = db_default
  195. self.editable = editable
  196. self.serialize = serialize
  197. self.unique_for_date = unique_for_date
  198. self.unique_for_month = unique_for_month
  199. self.unique_for_year = unique_for_year
  200. self.choices = choices
  201. self.help_text = help_text
  202. self.db_index = db_index
  203. self.db_column = db_column
  204. self.db_comment = db_comment
  205. self._db_tablespace = db_tablespace
  206. self.auto_created = auto_created
  207. # Adjust the appropriate creation counter, and save our local copy.
  208. if auto_created:
  209. self.creation_counter = Field.auto_creation_counter
  210. Field.auto_creation_counter -= 1
  211. else:
  212. self.creation_counter = Field.creation_counter
  213. Field.creation_counter += 1
  214. self._validators = list(validators) # Store for deconstruction later
  215. self._error_messages = error_messages # Store for deconstruction later
  216. def __str__(self):
  217. """
  218. Return "app_label.model_label.field_name" for fields attached to
  219. models.
  220. """
  221. if not hasattr(self, "model"):
  222. return super().__str__()
  223. model = self.model
  224. return "%s.%s" % (model._meta.label, self.name)
  225. def __repr__(self):
  226. """Display the module, class, and name of the field."""
  227. path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__)
  228. name = getattr(self, "name", None)
  229. if name is not None:
  230. return "<%s: %s>" % (path, name)
  231. return "<%s>" % path
  232. def check(self, **kwargs):
  233. return [
  234. *self._check_field_name(),
  235. *self._check_choices(),
  236. *self._check_db_default(**kwargs),
  237. *self._check_db_index(),
  238. *self._check_db_comment(**kwargs),
  239. *self._check_null_allowed_for_primary_keys(),
  240. *self._check_backend_specific_checks(**kwargs),
  241. *self._check_validators(),
  242. *self._check_deprecation_details(),
  243. ]
  244. def _check_field_name(self):
  245. """
  246. Check if field name is valid, i.e. 1) does not end with an
  247. underscore, 2) does not contain "__" and 3) is not "pk".
  248. """
  249. if self.name is None:
  250. return []
  251. if self.name.endswith("_"):
  252. return [
  253. checks.Error(
  254. "Field names must not end with an underscore.",
  255. obj=self,
  256. id="fields.E001",
  257. )
  258. ]
  259. elif LOOKUP_SEP in self.name:
  260. return [
  261. checks.Error(
  262. 'Field names must not contain "%s".' % LOOKUP_SEP,
  263. obj=self,
  264. id="fields.E002",
  265. )
  266. ]
  267. elif self.name == "pk":
  268. return [
  269. checks.Error(
  270. "'pk' is a reserved word that cannot be used as a field name.",
  271. obj=self,
  272. id="fields.E003",
  273. )
  274. ]
  275. else:
  276. return []
  277. @classmethod
  278. def _choices_is_value(cls, value):
  279. return isinstance(value, (str, Promise)) or not is_iterable(value)
  280. def _check_choices(self):
  281. if not self.choices:
  282. return []
  283. if not is_iterable(self.choices) or isinstance(self.choices, str):
  284. return [
  285. checks.Error(
  286. "'choices' must be a mapping (e.g. a dictionary) or an iterable "
  287. "(e.g. a list or tuple).",
  288. obj=self,
  289. id="fields.E004",
  290. )
  291. ]
  292. choice_max_length = 0
  293. # Expect [group_name, [value, display]]
  294. for choices_group in self.choices:
  295. try:
  296. group_name, group_choices = choices_group
  297. except (TypeError, ValueError):
  298. # Containing non-pairs
  299. break
  300. try:
  301. if not all(
  302. self._choices_is_value(value) and self._choices_is_value(human_name)
  303. for value, human_name in group_choices
  304. ):
  305. break
  306. if self.max_length is not None and group_choices:
  307. choice_max_length = max(
  308. [
  309. choice_max_length,
  310. *(
  311. len(value)
  312. for value, _ in group_choices
  313. if isinstance(value, str)
  314. ),
  315. ]
  316. )
  317. except (TypeError, ValueError):
  318. # No groups, choices in the form [value, display]
  319. value, human_name = group_name, group_choices
  320. if not self._choices_is_value(value) or not self._choices_is_value(
  321. human_name
  322. ):
  323. break
  324. if self.max_length is not None and isinstance(value, str):
  325. choice_max_length = max(choice_max_length, len(value))
  326. # Special case: choices=['ab']
  327. if isinstance(choices_group, str):
  328. break
  329. else:
  330. if self.max_length is not None and choice_max_length > self.max_length:
  331. return [
  332. checks.Error(
  333. "'max_length' is too small to fit the longest value "
  334. "in 'choices' (%d characters)." % choice_max_length,
  335. obj=self,
  336. id="fields.E009",
  337. ),
  338. ]
  339. return []
  340. return [
  341. checks.Error(
  342. "'choices' must be a mapping of actual values to human readable names "
  343. "or an iterable containing (actual value, human readable name) tuples.",
  344. obj=self,
  345. id="fields.E005",
  346. )
  347. ]
  348. def _check_db_default(self, databases=None, **kwargs):
  349. from django.db.models.expressions import Value
  350. if (
  351. self.db_default is NOT_PROVIDED
  352. or isinstance(self.db_default, Value)
  353. or databases is None
  354. ):
  355. return []
  356. errors = []
  357. for db in databases:
  358. if not router.allow_migrate_model(db, self.model):
  359. continue
  360. connection = connections[db]
  361. if not getattr(self._db_default_expression, "allowed_default", False) and (
  362. connection.features.supports_expression_defaults
  363. ):
  364. msg = f"{self.db_default} cannot be used in db_default."
  365. errors.append(checks.Error(msg, obj=self, id="fields.E012"))
  366. if not (
  367. connection.features.supports_expression_defaults
  368. or "supports_expression_defaults"
  369. in self.model._meta.required_db_features
  370. ):
  371. msg = (
  372. f"{connection.display_name} does not support default database "
  373. "values with expressions (db_default)."
  374. )
  375. errors.append(checks.Error(msg, obj=self, id="fields.E011"))
  376. return errors
  377. def _check_db_index(self):
  378. if self.db_index not in (None, True, False):
  379. return [
  380. checks.Error(
  381. "'db_index' must be None, True or False.",
  382. obj=self,
  383. id="fields.E006",
  384. )
  385. ]
  386. else:
  387. return []
  388. def _check_db_comment(self, databases=None, **kwargs):
  389. if not self.db_comment or not databases:
  390. return []
  391. errors = []
  392. for db in databases:
  393. if not router.allow_migrate_model(db, self.model):
  394. continue
  395. connection = connections[db]
  396. if not (
  397. connection.features.supports_comments
  398. or "supports_comments" in self.model._meta.required_db_features
  399. ):
  400. errors.append(
  401. checks.Warning(
  402. f"{connection.display_name} does not support comments on "
  403. f"columns (db_comment).",
  404. obj=self,
  405. id="fields.W163",
  406. )
  407. )
  408. return errors
  409. def _check_null_allowed_for_primary_keys(self):
  410. if (
  411. self.primary_key
  412. and self.null
  413. and not connection.features.interprets_empty_strings_as_nulls
  414. ):
  415. # We cannot reliably check this for backends like Oracle which
  416. # consider NULL and '' to be equal (and thus set up
  417. # character-based fields a little differently).
  418. return [
  419. checks.Error(
  420. "Primary keys must not have null=True.",
  421. hint=(
  422. "Set null=False on the field, or "
  423. "remove primary_key=True argument."
  424. ),
  425. obj=self,
  426. id="fields.E007",
  427. )
  428. ]
  429. else:
  430. return []
  431. def _check_backend_specific_checks(self, databases=None, **kwargs):
  432. if databases is None:
  433. return []
  434. errors = []
  435. for alias in databases:
  436. if router.allow_migrate_model(alias, self.model):
  437. errors.extend(connections[alias].validation.check_field(self, **kwargs))
  438. return errors
  439. def _check_validators(self):
  440. errors = []
  441. for i, validator in enumerate(self.validators):
  442. if not callable(validator):
  443. errors.append(
  444. checks.Error(
  445. "All 'validators' must be callable.",
  446. hint=(
  447. "validators[{i}] ({repr}) isn't a function or "
  448. "instance of a validator class.".format(
  449. i=i,
  450. repr=repr(validator),
  451. )
  452. ),
  453. obj=self,
  454. id="fields.E008",
  455. )
  456. )
  457. return errors
  458. def _check_deprecation_details(self):
  459. if self.system_check_removed_details is not None:
  460. return [
  461. checks.Error(
  462. self.system_check_removed_details.get(
  463. "msg",
  464. "%s has been removed except for support in historical "
  465. "migrations." % self.__class__.__name__,
  466. ),
  467. hint=self.system_check_removed_details.get("hint"),
  468. obj=self,
  469. id=self.system_check_removed_details.get("id", "fields.EXXX"),
  470. )
  471. ]
  472. elif self.system_check_deprecated_details is not None:
  473. return [
  474. checks.Warning(
  475. self.system_check_deprecated_details.get(
  476. "msg", "%s has been deprecated." % self.__class__.__name__
  477. ),
  478. hint=self.system_check_deprecated_details.get("hint"),
  479. obj=self,
  480. id=self.system_check_deprecated_details.get("id", "fields.WXXX"),
  481. )
  482. ]
  483. return []
  484. def get_col(self, alias, output_field=None):
  485. if alias == self.model._meta.db_table and (
  486. output_field is None or output_field == self
  487. ):
  488. return self.cached_col
  489. from django.db.models.expressions import Col
  490. return Col(alias, self, output_field)
  491. @property
  492. def choices(self):
  493. return self._choices
  494. @choices.setter
  495. def choices(self, value):
  496. self._choices = normalize_choices(value)
  497. @cached_property
  498. def cached_col(self):
  499. from django.db.models.expressions import Col
  500. return Col(self.model._meta.db_table, self)
  501. def select_format(self, compiler, sql, params):
  502. """
  503. Custom format for select clauses. For example, GIS columns need to be
  504. selected as AsText(table.col) on MySQL as the table.col data can't be
  505. used by Django.
  506. """
  507. return sql, params
  508. def deconstruct(self):
  509. """
  510. Return enough information to recreate the field as a 4-tuple:
  511. * The name of the field on the model, if contribute_to_class() has
  512. been run.
  513. * The import path of the field, including the class, e.g.
  514. django.db.models.IntegerField. This should be the most portable
  515. version, so less specific may be better.
  516. * A list of positional arguments.
  517. * A dict of keyword arguments.
  518. Note that the positional or keyword arguments must contain values of
  519. the following types (including inner values of collection types):
  520. * None, bool, str, int, float, complex, set, frozenset, list, tuple,
  521. dict
  522. * UUID
  523. * datetime.datetime (naive), datetime.date
  524. * top-level classes, top-level functions - will be referenced by their
  525. full import path
  526. * Storage instances - these have their own deconstruct() method
  527. This is because the values here must be serialized into a text format
  528. (possibly new Python code, possibly JSON) and these are the only types
  529. with encoding handlers defined.
  530. There's no need to return the exact way the field was instantiated this
  531. time, just ensure that the resulting field is the same - prefer keyword
  532. arguments over positional ones, and omit parameters with their default
  533. values.
  534. """
  535. # Short-form way of fetching all the default parameters
  536. keywords = {}
  537. possibles = {
  538. "verbose_name": None,
  539. "primary_key": False,
  540. "max_length": None,
  541. "unique": False,
  542. "blank": False,
  543. "null": False,
  544. "db_index": False,
  545. "default": NOT_PROVIDED,
  546. "db_default": NOT_PROVIDED,
  547. "editable": True,
  548. "serialize": True,
  549. "unique_for_date": None,
  550. "unique_for_month": None,
  551. "unique_for_year": None,
  552. "choices": None,
  553. "help_text": "",
  554. "db_column": None,
  555. "db_comment": None,
  556. "db_tablespace": None,
  557. "auto_created": False,
  558. "validators": [],
  559. "error_messages": None,
  560. }
  561. attr_overrides = {
  562. "unique": "_unique",
  563. "error_messages": "_error_messages",
  564. "validators": "_validators",
  565. "verbose_name": "_verbose_name",
  566. "db_tablespace": "_db_tablespace",
  567. }
  568. equals_comparison = {"choices", "validators"}
  569. for name, default in possibles.items():
  570. value = getattr(self, attr_overrides.get(name, name))
  571. if isinstance(value, CallableChoiceIterator):
  572. value = value.func
  573. # Do correct kind of comparison
  574. if name in equals_comparison:
  575. if value != default:
  576. keywords[name] = value
  577. else:
  578. if value is not default:
  579. keywords[name] = value
  580. # Work out path - we shorten it for known Django core fields
  581. path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__)
  582. if path.startswith("django.db.models.fields.related"):
  583. path = path.replace("django.db.models.fields.related", "django.db.models")
  584. elif path.startswith("django.db.models.fields.files"):
  585. path = path.replace("django.db.models.fields.files", "django.db.models")
  586. elif path.startswith("django.db.models.fields.generated"):
  587. path = path.replace("django.db.models.fields.generated", "django.db.models")
  588. elif path.startswith("django.db.models.fields.json"):
  589. path = path.replace("django.db.models.fields.json", "django.db.models")
  590. elif path.startswith("django.db.models.fields.proxy"):
  591. path = path.replace("django.db.models.fields.proxy", "django.db.models")
  592. elif path.startswith("django.db.models.fields"):
  593. path = path.replace("django.db.models.fields", "django.db.models")
  594. # Return basic info - other fields should override this.
  595. return (self.name, path, [], keywords)
  596. def clone(self):
  597. """
  598. Uses deconstruct() to clone a new copy of this Field.
  599. Will not preserve any class attachments/attribute names.
  600. """
  601. name, path, args, kwargs = self.deconstruct()
  602. return self.__class__(*args, **kwargs)
  603. def __eq__(self, other):
  604. # Needed for @total_ordering
  605. if isinstance(other, Field):
  606. return self.creation_counter == other.creation_counter and getattr(
  607. self, "model", None
  608. ) == getattr(other, "model", None)
  609. return NotImplemented
  610. def __lt__(self, other):
  611. # This is needed because bisect does not take a comparison function.
  612. # Order by creation_counter first for backward compatibility.
  613. if isinstance(other, Field):
  614. if (
  615. self.creation_counter != other.creation_counter
  616. or not hasattr(self, "model")
  617. and not hasattr(other, "model")
  618. ):
  619. return self.creation_counter < other.creation_counter
  620. elif hasattr(self, "model") != hasattr(other, "model"):
  621. return not hasattr(self, "model") # Order no-model fields first
  622. else:
  623. # creation_counter's are equal, compare only models.
  624. return (self.model._meta.app_label, self.model._meta.model_name) < (
  625. other.model._meta.app_label,
  626. other.model._meta.model_name,
  627. )
  628. return NotImplemented
  629. def __hash__(self):
  630. return hash(self.creation_counter)
  631. def __deepcopy__(self, memodict):
  632. # We don't have to deepcopy very much here, since most things are not
  633. # intended to be altered after initial creation.
  634. obj = copy.copy(self)
  635. if self.remote_field:
  636. obj.remote_field = copy.copy(self.remote_field)
  637. if hasattr(self.remote_field, "field") and self.remote_field.field is self:
  638. obj.remote_field.field = obj
  639. memodict[id(self)] = obj
  640. return obj
  641. def __copy__(self):
  642. # We need to avoid hitting __reduce__, so define this
  643. # slightly weird copy construct.
  644. obj = Empty()
  645. obj.__class__ = self.__class__
  646. obj.__dict__ = self.__dict__.copy()
  647. return obj
  648. def __reduce__(self):
  649. """
  650. Pickling should return the model._meta.fields instance of the field,
  651. not a new copy of that field. So, use the app registry to load the
  652. model and then the field back.
  653. """
  654. if not hasattr(self, "model"):
  655. # Fields are sometimes used without attaching them to models (for
  656. # example in aggregation). In this case give back a plain field
  657. # instance. The code below will create a new empty instance of
  658. # class self.__class__, then update its dict with self.__dict__
  659. # values - so, this is very close to normal pickle.
  660. state = self.__dict__.copy()
  661. # The _get_default cached_property can't be pickled due to lambda
  662. # usage.
  663. state.pop("_get_default", None)
  664. return _empty, (self.__class__,), state
  665. return _load_field, (
  666. self.model._meta.app_label,
  667. self.model._meta.object_name,
  668. self.name,
  669. )
  670. def get_pk_value_on_save(self, instance):
  671. """
  672. Hook to generate new PK values on save. This method is called when
  673. saving instances with no primary key value set. If this method returns
  674. something else than None, then the returned value is used when saving
  675. the new instance.
  676. """
  677. if self.default:
  678. return self.get_default()
  679. return None
  680. def to_python(self, value):
  681. """
  682. Convert the input value into the expected Python data type, raising
  683. django.core.exceptions.ValidationError if the data can't be converted.
  684. Return the converted value. Subclasses should override this.
  685. """
  686. return value
  687. @cached_property
  688. def error_messages(self):
  689. messages = {}
  690. for c in reversed(self.__class__.__mro__):
  691. messages.update(getattr(c, "default_error_messages", {}))
  692. messages.update(self._error_messages or {})
  693. return messages
  694. @cached_property
  695. def validators(self):
  696. """
  697. Some validators can't be created at field initialization time.
  698. This method provides a way to delay their creation until required.
  699. """
  700. return [*self.default_validators, *self._validators]
  701. def run_validators(self, value):
  702. if value in self.empty_values:
  703. return
  704. errors = []
  705. for v in self.validators:
  706. try:
  707. v(value)
  708. except exceptions.ValidationError as e:
  709. if hasattr(e, "code") and e.code in self.error_messages:
  710. e.message = self.error_messages[e.code]
  711. errors.extend(e.error_list)
  712. if errors:
  713. raise exceptions.ValidationError(errors)
  714. def validate(self, value, model_instance):
  715. """
  716. Validate value and raise ValidationError if necessary. Subclasses
  717. should override this to provide validation logic.
  718. """
  719. if not self.editable:
  720. # Skip validation for non-editable fields.
  721. return
  722. if self.choices is not None and value not in self.empty_values:
  723. for option_key, option_value in self.choices:
  724. if isinstance(option_value, (list, tuple)):
  725. # This is an optgroup, so look inside the group for
  726. # options.
  727. for optgroup_key, optgroup_value in option_value:
  728. if value == optgroup_key:
  729. return
  730. elif value == option_key:
  731. return
  732. raise exceptions.ValidationError(
  733. self.error_messages["invalid_choice"],
  734. code="invalid_choice",
  735. params={"value": value},
  736. )
  737. if value is None and not self.null:
  738. raise exceptions.ValidationError(self.error_messages["null"], code="null")
  739. if not self.blank and value in self.empty_values:
  740. raise exceptions.ValidationError(self.error_messages["blank"], code="blank")
  741. def clean(self, value, model_instance):
  742. """
  743. Convert the value's type and run validation. Validation errors
  744. from to_python() and validate() are propagated. Return the correct
  745. value if no error is raised.
  746. """
  747. value = self.to_python(value)
  748. self.validate(value, model_instance)
  749. self.run_validators(value)
  750. return value
  751. def db_type_parameters(self, connection):
  752. return DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
  753. def db_check(self, connection):
  754. """
  755. Return the database column check constraint for this field, for the
  756. provided connection. Works the same way as db_type() for the case that
  757. get_internal_type() does not map to a preexisting model field.
  758. """
  759. data = self.db_type_parameters(connection)
  760. try:
  761. return (
  762. connection.data_type_check_constraints[self.get_internal_type()] % data
  763. )
  764. except KeyError:
  765. return None
  766. def db_type(self, connection):
  767. """
  768. Return the database column data type for this field, for the provided
  769. connection.
  770. """
  771. # The default implementation of this method looks at the
  772. # backend-specific data_types dictionary, looking up the field by its
  773. # "internal type".
  774. #
  775. # A Field class can implement the get_internal_type() method to specify
  776. # which *preexisting* Django Field class it's most similar to -- i.e.,
  777. # a custom field might be represented by a TEXT column type, which is
  778. # the same as the TextField Django field type, which means the custom
  779. # field's get_internal_type() returns 'TextField'.
  780. #
  781. # But the limitation of the get_internal_type() / data_types approach
  782. # is that it cannot handle database column types that aren't already
  783. # mapped to one of the built-in Django field types. In this case, you
  784. # can implement db_type() instead of get_internal_type() to specify
  785. # exactly which wacky database column type you want to use.
  786. data = self.db_type_parameters(connection)
  787. try:
  788. column_type = connection.data_types[self.get_internal_type()]
  789. except KeyError:
  790. return None
  791. else:
  792. # column_type is either a single-parameter function or a string.
  793. if callable(column_type):
  794. return column_type(data)
  795. return column_type % data
  796. def rel_db_type(self, connection):
  797. """
  798. Return the data type that a related field pointing to this field should
  799. use. For example, this method is called by ForeignKey and OneToOneField
  800. to determine its data type.
  801. """
  802. return self.db_type(connection)
  803. def cast_db_type(self, connection):
  804. """Return the data type to use in the Cast() function."""
  805. db_type = connection.ops.cast_data_types.get(self.get_internal_type())
  806. if db_type:
  807. return db_type % self.db_type_parameters(connection)
  808. return self.db_type(connection)
  809. def db_parameters(self, connection):
  810. """
  811. Extension of db_type(), providing a range of different return values
  812. (type, checks). This will look at db_type(), allowing custom model
  813. fields to override it.
  814. """
  815. type_string = self.db_type(connection)
  816. check_string = self.db_check(connection)
  817. return {
  818. "type": type_string,
  819. "check": check_string,
  820. }
  821. def db_type_suffix(self, connection):
  822. return connection.data_types_suffix.get(self.get_internal_type())
  823. def get_db_converters(self, connection):
  824. if hasattr(self, "from_db_value"):
  825. return [self.from_db_value]
  826. return []
  827. @property
  828. def unique(self):
  829. return self._unique or self.primary_key
  830. @property
  831. def db_tablespace(self):
  832. return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
  833. @property
  834. def db_returning(self):
  835. """Private API intended only to be used by Django itself."""
  836. return (
  837. self.db_default is not NOT_PROVIDED
  838. and connection.features.can_return_columns_from_insert
  839. )
  840. def set_attributes_from_name(self, name):
  841. self.name = self.name or name
  842. self.attname, self.column = self.get_attname_column()
  843. self.concrete = self.column is not None
  844. if self.verbose_name is None and self.name:
  845. self.verbose_name = self.name.replace("_", " ")
  846. def contribute_to_class(self, cls, name, private_only=False):
  847. """
  848. Register the field with the model class it belongs to.
  849. If private_only is True, create a separate instance of this field
  850. for every subclass of cls, even if cls is not an abstract model.
  851. """
  852. self.set_attributes_from_name(name)
  853. self.model = cls
  854. cls._meta.add_field(self, private=private_only)
  855. if self.column:
  856. setattr(cls, self.attname, self.descriptor_class(self))
  857. if self.choices is not None:
  858. # Don't override a get_FOO_display() method defined explicitly on
  859. # this class, but don't check methods derived from inheritance, to
  860. # allow overriding inherited choices. For more complex inheritance
  861. # structures users should override contribute_to_class().
  862. if "get_%s_display" % self.name not in cls.__dict__:
  863. setattr(
  864. cls,
  865. "get_%s_display" % self.name,
  866. partialmethod(cls._get_FIELD_display, field=self),
  867. )
  868. def get_filter_kwargs_for_object(self, obj):
  869. """
  870. Return a dict that when passed as kwargs to self.model.filter(), would
  871. yield all instances having the same value for this field as obj has.
  872. """
  873. return {self.name: getattr(obj, self.attname)}
  874. def get_attname(self):
  875. return self.name
  876. def get_attname_column(self):
  877. attname = self.get_attname()
  878. column = self.db_column or attname
  879. return attname, column
  880. def get_internal_type(self):
  881. return self.__class__.__name__
  882. def pre_save(self, model_instance, add):
  883. """Return field's value just before saving."""
  884. return getattr(model_instance, self.attname)
  885. def get_prep_value(self, value):
  886. """Perform preliminary non-db specific value checks and conversions."""
  887. if isinstance(value, Promise):
  888. value = value._proxy____cast()
  889. return value
  890. def get_db_prep_value(self, value, connection, prepared=False):
  891. """
  892. Return field's value prepared for interacting with the database backend.
  893. Used by the default implementations of get_db_prep_save().
  894. """
  895. if not prepared:
  896. value = self.get_prep_value(value)
  897. return value
  898. def get_db_prep_save(self, value, connection):
  899. """Return field's value prepared for saving into a database."""
  900. if hasattr(value, "as_sql"):
  901. return value
  902. return self.get_db_prep_value(value, connection=connection, prepared=False)
  903. def has_default(self):
  904. """Return a boolean of whether this field has a default value."""
  905. return self.default is not NOT_PROVIDED
  906. def get_default(self):
  907. """Return the default value for this field."""
  908. return self._get_default()
  909. @cached_property
  910. def _get_default(self):
  911. if self.has_default():
  912. if callable(self.default):
  913. return self.default
  914. return lambda: self.default
  915. if self.db_default is not NOT_PROVIDED:
  916. from django.db.models.expressions import DatabaseDefault
  917. return lambda: DatabaseDefault(
  918. self._db_default_expression, output_field=self
  919. )
  920. if (
  921. not self.empty_strings_allowed
  922. or self.null
  923. and not connection.features.interprets_empty_strings_as_nulls
  924. ):
  925. return return_None
  926. return str # return empty string
  927. @cached_property
  928. def _db_default_expression(self):
  929. db_default = self.db_default
  930. if db_default is not NOT_PROVIDED and not hasattr(
  931. db_default, "resolve_expression"
  932. ):
  933. from django.db.models.expressions import Value
  934. db_default = Value(db_default, self)
  935. return db_default
  936. def get_choices(
  937. self,
  938. include_blank=True,
  939. blank_choice=BLANK_CHOICE_DASH,
  940. limit_choices_to=None,
  941. ordering=(),
  942. ):
  943. """
  944. Return choices with a default blank choices included, for use
  945. as <select> choices for this field.
  946. """
  947. if self.choices is not None:
  948. if include_blank:
  949. return BlankChoiceIterator(self.choices, blank_choice)
  950. return self.choices
  951. rel_model = self.remote_field.model
  952. limit_choices_to = limit_choices_to or self.get_limit_choices_to()
  953. choice_func = operator.attrgetter(
  954. self.remote_field.get_related_field().attname
  955. if hasattr(self.remote_field, "get_related_field")
  956. else "pk"
  957. )
  958. qs = rel_model._default_manager.complex_filter(limit_choices_to)
  959. if ordering:
  960. qs = qs.order_by(*ordering)
  961. return (blank_choice if include_blank else []) + [
  962. (choice_func(x), str(x)) for x in qs
  963. ]
  964. def value_to_string(self, obj):
  965. """
  966. Return a string value of this field from the passed obj.
  967. This is used by the serialization framework.
  968. """
  969. return str(self.value_from_object(obj))
  970. @property
  971. def flatchoices(self):
  972. """Flattened version of choices tuple."""
  973. return list(flatten_choices(self.choices))
  974. def save_form_data(self, instance, data):
  975. setattr(instance, self.name, data)
  976. def formfield(self, form_class=None, choices_form_class=None, **kwargs):
  977. """Return a django.forms.Field instance for this field."""
  978. defaults = {
  979. "required": not self.blank,
  980. "label": capfirst(self.verbose_name),
  981. "help_text": self.help_text,
  982. }
  983. if self.has_default():
  984. if callable(self.default):
  985. defaults["initial"] = self.default
  986. defaults["show_hidden_initial"] = True
  987. else:
  988. defaults["initial"] = self.get_default()
  989. if self.choices is not None:
  990. # Fields with choices get special treatment.
  991. include_blank = self.blank or not (
  992. self.has_default() or "initial" in kwargs
  993. )
  994. defaults["choices"] = self.get_choices(include_blank=include_blank)
  995. defaults["coerce"] = self.to_python
  996. if self.null:
  997. defaults["empty_value"] = None
  998. if choices_form_class is not None:
  999. form_class = choices_form_class
  1000. else:
  1001. form_class = forms.TypedChoiceField
  1002. # Many of the subclass-specific formfield arguments (min_value,
  1003. # max_value) don't apply for choice fields, so be sure to only pass
  1004. # the values that TypedChoiceField will understand.
  1005. for k in list(kwargs):
  1006. if k not in (
  1007. "coerce",
  1008. "empty_value",
  1009. "choices",
  1010. "required",
  1011. "widget",
  1012. "label",
  1013. "initial",
  1014. "help_text",
  1015. "error_messages",
  1016. "show_hidden_initial",
  1017. "disabled",
  1018. ):
  1019. del kwargs[k]
  1020. defaults.update(kwargs)
  1021. if form_class is None:
  1022. form_class = forms.CharField
  1023. return form_class(**defaults)
  1024. def value_from_object(self, obj):
  1025. """Return the value of this field in the given model instance."""
  1026. return getattr(obj, self.attname)
  1027. class BooleanField(Field):
  1028. empty_strings_allowed = False
  1029. default_error_messages = {
  1030. "invalid": _("“%(value)s” value must be either True or False."),
  1031. "invalid_nullable": _("“%(value)s” value must be either True, False, or None."),
  1032. }
  1033. description = _("Boolean (Either True or False)")
  1034. def get_internal_type(self):
  1035. return "BooleanField"
  1036. def to_python(self, value):
  1037. if self.null and value in self.empty_values:
  1038. return None
  1039. if value in (True, False):
  1040. # 1/0 are equal to True/False. bool() converts former to latter.
  1041. return bool(value)
  1042. if value in ("t", "True", "1"):
  1043. return True
  1044. if value in ("f", "False", "0"):
  1045. return False
  1046. raise exceptions.ValidationError(
  1047. self.error_messages["invalid_nullable" if self.null else "invalid"],
  1048. code="invalid",
  1049. params={"value": value},
  1050. )
  1051. def get_prep_value(self, value):
  1052. value = super().get_prep_value(value)
  1053. if value is None:
  1054. return None
  1055. return self.to_python(value)
  1056. def formfield(self, **kwargs):
  1057. if self.choices is not None:
  1058. include_blank = not (self.has_default() or "initial" in kwargs)
  1059. defaults = {"choices": self.get_choices(include_blank=include_blank)}
  1060. else:
  1061. form_class = forms.NullBooleanField if self.null else forms.BooleanField
  1062. # In HTML checkboxes, 'required' means "must be checked" which is
  1063. # different from the choices case ("must select some value").
  1064. # required=False allows unchecked checkboxes.
  1065. defaults = {"form_class": form_class, "required": False}
  1066. return super().formfield(**{**defaults, **kwargs})
  1067. class CharField(Field):
  1068. def __init__(self, *args, db_collation=None, **kwargs):
  1069. super().__init__(*args, **kwargs)
  1070. self.db_collation = db_collation
  1071. if self.max_length is not None:
  1072. self.validators.append(validators.MaxLengthValidator(self.max_length))
  1073. @property
  1074. def description(self):
  1075. if self.max_length is not None:
  1076. return _("String (up to %(max_length)s)")
  1077. else:
  1078. return _("String (unlimited)")
  1079. def check(self, **kwargs):
  1080. databases = kwargs.get("databases") or []
  1081. return [
  1082. *super().check(**kwargs),
  1083. *self._check_db_collation(databases),
  1084. *self._check_max_length_attribute(**kwargs),
  1085. ]
  1086. def _check_max_length_attribute(self, **kwargs):
  1087. if self.max_length is None:
  1088. if (
  1089. connection.features.supports_unlimited_charfield
  1090. or "supports_unlimited_charfield"
  1091. in self.model._meta.required_db_features
  1092. ):
  1093. return []
  1094. return [
  1095. checks.Error(
  1096. "CharFields must define a 'max_length' attribute.",
  1097. obj=self,
  1098. id="fields.E120",
  1099. )
  1100. ]
  1101. elif (
  1102. not isinstance(self.max_length, int)
  1103. or isinstance(self.max_length, bool)
  1104. or self.max_length <= 0
  1105. ):
  1106. return [
  1107. checks.Error(
  1108. "'max_length' must be a positive integer.",
  1109. obj=self,
  1110. id="fields.E121",
  1111. )
  1112. ]
  1113. else:
  1114. return []
  1115. def _check_db_collation(self, databases):
  1116. errors = []
  1117. for db in databases:
  1118. if not router.allow_migrate_model(db, self.model):
  1119. continue
  1120. connection = connections[db]
  1121. if not (
  1122. self.db_collation is None
  1123. or "supports_collation_on_charfield"
  1124. in self.model._meta.required_db_features
  1125. or connection.features.supports_collation_on_charfield
  1126. ):
  1127. errors.append(
  1128. checks.Error(
  1129. "%s does not support a database collation on "
  1130. "CharFields." % connection.display_name,
  1131. obj=self,
  1132. id="fields.E190",
  1133. ),
  1134. )
  1135. return errors
  1136. def cast_db_type(self, connection):
  1137. if self.max_length is None:
  1138. return connection.ops.cast_char_field_without_max_length
  1139. return super().cast_db_type(connection)
  1140. def db_parameters(self, connection):
  1141. db_params = super().db_parameters(connection)
  1142. db_params["collation"] = self.db_collation
  1143. return db_params
  1144. def get_internal_type(self):
  1145. return "CharField"
  1146. def to_python(self, value):
  1147. if isinstance(value, str) or value is None:
  1148. return value
  1149. return str(value)
  1150. def get_prep_value(self, value):
  1151. value = super().get_prep_value(value)
  1152. return self.to_python(value)
  1153. def formfield(self, **kwargs):
  1154. # Passing max_length to forms.CharField means that the value's length
  1155. # will be validated twice. This is considered acceptable since we want
  1156. # the value in the form field (to pass into widget for example).
  1157. defaults = {"max_length": self.max_length}
  1158. # TODO: Handle multiple backends with different feature flags.
  1159. if self.null and not connection.features.interprets_empty_strings_as_nulls:
  1160. defaults["empty_value"] = None
  1161. defaults.update(kwargs)
  1162. return super().formfield(**defaults)
  1163. def deconstruct(self):
  1164. name, path, args, kwargs = super().deconstruct()
  1165. if self.db_collation:
  1166. kwargs["db_collation"] = self.db_collation
  1167. return name, path, args, kwargs
  1168. class CommaSeparatedIntegerField(CharField):
  1169. default_validators = [validators.validate_comma_separated_integer_list]
  1170. description = _("Comma-separated integers")
  1171. system_check_removed_details = {
  1172. "msg": (
  1173. "CommaSeparatedIntegerField is removed except for support in "
  1174. "historical migrations."
  1175. ),
  1176. "hint": (
  1177. "Use CharField(validators=[validate_comma_separated_integer_list]) "
  1178. "instead."
  1179. ),
  1180. "id": "fields.E901",
  1181. }
  1182. def _to_naive(value):
  1183. if timezone.is_aware(value):
  1184. value = timezone.make_naive(value, datetime.timezone.utc)
  1185. return value
  1186. def _get_naive_now():
  1187. return _to_naive(timezone.now())
  1188. class DateTimeCheckMixin:
  1189. def check(self, **kwargs):
  1190. return [
  1191. *super().check(**kwargs),
  1192. *self._check_mutually_exclusive_options(),
  1193. *self._check_fix_default_value(),
  1194. ]
  1195. def _check_mutually_exclusive_options(self):
  1196. # auto_now, auto_now_add, and default are mutually exclusive
  1197. # options. The use of more than one of these options together
  1198. # will trigger an Error
  1199. mutually_exclusive_options = [
  1200. self.auto_now_add,
  1201. self.auto_now,
  1202. self.has_default(),
  1203. ]
  1204. enabled_options = [
  1205. option not in (None, False) for option in mutually_exclusive_options
  1206. ].count(True)
  1207. if enabled_options > 1:
  1208. return [
  1209. checks.Error(
  1210. "The options auto_now, auto_now_add, and default "
  1211. "are mutually exclusive. Only one of these options "
  1212. "may be present.",
  1213. obj=self,
  1214. id="fields.E160",
  1215. )
  1216. ]
  1217. else:
  1218. return []
  1219. def _check_fix_default_value(self):
  1220. return []
  1221. # Concrete subclasses use this in their implementations of
  1222. # _check_fix_default_value().
  1223. def _check_if_value_fixed(self, value, now=None):
  1224. """
  1225. Check if the given value appears to have been provided as a "fixed"
  1226. time value, and include a warning in the returned list if it does. The
  1227. value argument must be a date object or aware/naive datetime object. If
  1228. now is provided, it must be a naive datetime object.
  1229. """
  1230. if now is None:
  1231. now = _get_naive_now()
  1232. offset = datetime.timedelta(seconds=10)
  1233. lower = now - offset
  1234. upper = now + offset
  1235. if isinstance(value, datetime.datetime):
  1236. value = _to_naive(value)
  1237. else:
  1238. assert isinstance(value, datetime.date)
  1239. lower = lower.date()
  1240. upper = upper.date()
  1241. if lower <= value <= upper:
  1242. return [
  1243. checks.Warning(
  1244. "Fixed default value provided.",
  1245. hint=(
  1246. "It seems you set a fixed date / time / datetime "
  1247. "value as default for this field. This may not be "
  1248. "what you want. If you want to have the current date "
  1249. "as default, use `django.utils.timezone.now`"
  1250. ),
  1251. obj=self,
  1252. id="fields.W161",
  1253. )
  1254. ]
  1255. return []
  1256. class DateField(DateTimeCheckMixin, Field):
  1257. empty_strings_allowed = False
  1258. default_error_messages = {
  1259. "invalid": _(
  1260. "“%(value)s” value has an invalid date format. It must be "
  1261. "in YYYY-MM-DD format."
  1262. ),
  1263. "invalid_date": _(
  1264. "“%(value)s” value has the correct format (YYYY-MM-DD) "
  1265. "but it is an invalid date."
  1266. ),
  1267. }
  1268. description = _("Date (without time)")
  1269. def __init__(
  1270. self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs
  1271. ):
  1272. self.auto_now, self.auto_now_add = auto_now, auto_now_add
  1273. if auto_now or auto_now_add:
  1274. kwargs["editable"] = False
  1275. kwargs["blank"] = True
  1276. super().__init__(verbose_name, name, **kwargs)
  1277. def _check_fix_default_value(self):
  1278. """
  1279. Warn that using an actual date or datetime value is probably wrong;
  1280. it's only evaluated on server startup.
  1281. """
  1282. if not self.has_default():
  1283. return []
  1284. value = self.default
  1285. if isinstance(value, datetime.datetime):
  1286. value = _to_naive(value).date()
  1287. elif isinstance(value, datetime.date):
  1288. pass
  1289. else:
  1290. # No explicit date / datetime value -- no checks necessary
  1291. return []
  1292. # At this point, value is a date object.
  1293. return self._check_if_value_fixed(value)
  1294. def deconstruct(self):
  1295. name, path, args, kwargs = super().deconstruct()
  1296. if self.auto_now:
  1297. kwargs["auto_now"] = True
  1298. if self.auto_now_add:
  1299. kwargs["auto_now_add"] = True
  1300. if self.auto_now or self.auto_now_add:
  1301. del kwargs["editable"]
  1302. del kwargs["blank"]
  1303. return name, path, args, kwargs
  1304. def get_internal_type(self):
  1305. return "DateField"
  1306. def to_python(self, value):
  1307. if value is None:
  1308. return value
  1309. if isinstance(value, datetime.datetime):
  1310. if settings.USE_TZ and timezone.is_aware(value):
  1311. # Convert aware datetimes to the default time zone
  1312. # before casting them to dates (#17742).
  1313. default_timezone = timezone.get_default_timezone()
  1314. value = timezone.make_naive(value, default_timezone)
  1315. return value.date()
  1316. if isinstance(value, datetime.date):
  1317. return value
  1318. try:
  1319. parsed = parse_date(value)
  1320. if parsed is not None:
  1321. return parsed
  1322. except ValueError:
  1323. raise exceptions.ValidationError(
  1324. self.error_messages["invalid_date"],
  1325. code="invalid_date",
  1326. params={"value": value},
  1327. )
  1328. raise exceptions.ValidationError(
  1329. self.error_messages["invalid"],
  1330. code="invalid",
  1331. params={"value": value},
  1332. )
  1333. def pre_save(self, model_instance, add):
  1334. if self.auto_now or (self.auto_now_add and add):
  1335. value = datetime.date.today()
  1336. setattr(model_instance, self.attname, value)
  1337. return value
  1338. else:
  1339. return super().pre_save(model_instance, add)
  1340. def contribute_to_class(self, cls, name, **kwargs):
  1341. super().contribute_to_class(cls, name, **kwargs)
  1342. if not self.null:
  1343. setattr(
  1344. cls,
  1345. "get_next_by_%s" % self.name,
  1346. partialmethod(
  1347. cls._get_next_or_previous_by_FIELD, field=self, is_next=True
  1348. ),
  1349. )
  1350. setattr(
  1351. cls,
  1352. "get_previous_by_%s" % self.name,
  1353. partialmethod(
  1354. cls._get_next_or_previous_by_FIELD, field=self, is_next=False
  1355. ),
  1356. )
  1357. def get_prep_value(self, value):
  1358. value = super().get_prep_value(value)
  1359. return self.to_python(value)
  1360. def get_db_prep_value(self, value, connection, prepared=False):
  1361. # Casts dates into the format expected by the backend
  1362. if not prepared:
  1363. value = self.get_prep_value(value)
  1364. return connection.ops.adapt_datefield_value(value)
  1365. def value_to_string(self, obj):
  1366. val = self.value_from_object(obj)
  1367. return "" if val is None else val.isoformat()
  1368. def formfield(self, **kwargs):
  1369. return super().formfield(
  1370. **{
  1371. "form_class": forms.DateField,
  1372. **kwargs,
  1373. }
  1374. )
  1375. class DateTimeField(DateField):
  1376. empty_strings_allowed = False
  1377. default_error_messages = {
  1378. "invalid": _(
  1379. "“%(value)s” value has an invalid format. It must be in "
  1380. "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."
  1381. ),
  1382. "invalid_date": _(
  1383. "“%(value)s” value has the correct format "
  1384. "(YYYY-MM-DD) but it is an invalid date."
  1385. ),
  1386. "invalid_datetime": _(
  1387. "“%(value)s” value has the correct format "
  1388. "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
  1389. "but it is an invalid date/time."
  1390. ),
  1391. }
  1392. description = _("Date (with time)")
  1393. # __init__ is inherited from DateField
  1394. def _check_fix_default_value(self):
  1395. """
  1396. Warn that using an actual date or datetime value is probably wrong;
  1397. it's only evaluated on server startup.
  1398. """
  1399. if not self.has_default():
  1400. return []
  1401. value = self.default
  1402. if isinstance(value, (datetime.datetime, datetime.date)):
  1403. return self._check_if_value_fixed(value)
  1404. # No explicit date / datetime value -- no checks necessary.
  1405. return []
  1406. def get_internal_type(self):
  1407. return "DateTimeField"
  1408. def to_python(self, value):
  1409. if value is None:
  1410. return value
  1411. if isinstance(value, datetime.datetime):
  1412. return value
  1413. if isinstance(value, datetime.date):
  1414. value = datetime.datetime(value.year, value.month, value.day)
  1415. if settings.USE_TZ:
  1416. # For backwards compatibility, interpret naive datetimes in
  1417. # local time. This won't work during DST change, but we can't
  1418. # do much about it, so we let the exceptions percolate up the
  1419. # call stack.
  1420. try:
  1421. name = f"{self.model.__name__}.{self.name}"
  1422. except AttributeError:
  1423. name = "(unbound)"
  1424. warnings.warn(
  1425. f"DateTimeField {name} received a naive datetime ({value}) while "
  1426. "time zone support is active.",
  1427. RuntimeWarning,
  1428. )
  1429. default_timezone = timezone.get_default_timezone()
  1430. value = timezone.make_aware(value, default_timezone)
  1431. return value
  1432. try:
  1433. parsed = parse_datetime(value)
  1434. if parsed is not None:
  1435. return parsed
  1436. except ValueError:
  1437. raise exceptions.ValidationError(
  1438. self.error_messages["invalid_datetime"],
  1439. code="invalid_datetime",
  1440. params={"value": value},
  1441. )
  1442. try:
  1443. parsed = parse_date(value)
  1444. if parsed is not None:
  1445. return datetime.datetime(parsed.year, parsed.month, parsed.day)
  1446. except ValueError:
  1447. raise exceptions.ValidationError(
  1448. self.error_messages["invalid_date"],
  1449. code="invalid_date",
  1450. params={"value": value},
  1451. )
  1452. raise exceptions.ValidationError(
  1453. self.error_messages["invalid"],
  1454. code="invalid",
  1455. params={"value": value},
  1456. )
  1457. def pre_save(self, model_instance, add):
  1458. if self.auto_now or (self.auto_now_add and add):
  1459. value = timezone.now()
  1460. setattr(model_instance, self.attname, value)
  1461. return value
  1462. else:
  1463. return super().pre_save(model_instance, add)
  1464. # contribute_to_class is inherited from DateField, it registers
  1465. # get_next_by_FOO and get_prev_by_FOO
  1466. def get_prep_value(self, value):
  1467. value = super().get_prep_value(value)
  1468. value = self.to_python(value)
  1469. if value is not None and settings.USE_TZ and timezone.is_naive(value):
  1470. # For backwards compatibility, interpret naive datetimes in local
  1471. # time. This won't work during DST change, but we can't do much
  1472. # about it, so we let the exceptions percolate up the call stack.
  1473. try:
  1474. name = "%s.%s" % (self.model.__name__, self.name)
  1475. except AttributeError:
  1476. name = "(unbound)"
  1477. warnings.warn(
  1478. "DateTimeField %s received a naive datetime (%s)"
  1479. " while time zone support is active." % (name, value),
  1480. RuntimeWarning,
  1481. )
  1482. default_timezone = timezone.get_default_timezone()
  1483. value = timezone.make_aware(value, default_timezone)
  1484. return value
  1485. def get_db_prep_value(self, value, connection, prepared=False):
  1486. # Casts datetimes into the format expected by the backend
  1487. if not prepared:
  1488. value = self.get_prep_value(value)
  1489. return connection.ops.adapt_datetimefield_value(value)
  1490. def value_to_string(self, obj):
  1491. val = self.value_from_object(obj)
  1492. return "" if val is None else val.isoformat()
  1493. def formfield(self, **kwargs):
  1494. return super().formfield(
  1495. **{
  1496. "form_class": forms.DateTimeField,
  1497. **kwargs,
  1498. }
  1499. )
  1500. class DecimalField(Field):
  1501. empty_strings_allowed = False
  1502. default_error_messages = {
  1503. "invalid": _("“%(value)s” value must be a decimal number."),
  1504. }
  1505. description = _("Decimal number")
  1506. def __init__(
  1507. self,
  1508. verbose_name=None,
  1509. name=None,
  1510. max_digits=None,
  1511. decimal_places=None,
  1512. **kwargs,
  1513. ):
  1514. self.max_digits, self.decimal_places = max_digits, decimal_places
  1515. super().__init__(verbose_name, name, **kwargs)
  1516. def check(self, **kwargs):
  1517. errors = super().check(**kwargs)
  1518. digits_errors = [
  1519. *self._check_decimal_places(),
  1520. *self._check_max_digits(),
  1521. ]
  1522. if not digits_errors:
  1523. errors.extend(self._check_decimal_places_and_max_digits(**kwargs))
  1524. else:
  1525. errors.extend(digits_errors)
  1526. return errors
  1527. def _check_decimal_places(self):
  1528. try:
  1529. decimal_places = int(self.decimal_places)
  1530. if decimal_places < 0:
  1531. raise ValueError()
  1532. except TypeError:
  1533. return [
  1534. checks.Error(
  1535. "DecimalFields must define a 'decimal_places' attribute.",
  1536. obj=self,
  1537. id="fields.E130",
  1538. )
  1539. ]
  1540. except ValueError:
  1541. return [
  1542. checks.Error(
  1543. "'decimal_places' must be a non-negative integer.",
  1544. obj=self,
  1545. id="fields.E131",
  1546. )
  1547. ]
  1548. else:
  1549. return []
  1550. def _check_max_digits(self):
  1551. try:
  1552. max_digits = int(self.max_digits)
  1553. if max_digits <= 0:
  1554. raise ValueError()
  1555. except TypeError:
  1556. return [
  1557. checks.Error(
  1558. "DecimalFields must define a 'max_digits' attribute.",
  1559. obj=self,
  1560. id="fields.E132",
  1561. )
  1562. ]
  1563. except ValueError:
  1564. return [
  1565. checks.Error(
  1566. "'max_digits' must be a positive integer.",
  1567. obj=self,
  1568. id="fields.E133",
  1569. )
  1570. ]
  1571. else:
  1572. return []
  1573. def _check_decimal_places_and_max_digits(self, **kwargs):
  1574. if int(self.decimal_places) > int(self.max_digits):
  1575. return [
  1576. checks.Error(
  1577. "'max_digits' must be greater or equal to 'decimal_places'.",
  1578. obj=self,
  1579. id="fields.E134",
  1580. )
  1581. ]
  1582. return []
  1583. @cached_property
  1584. def validators(self):
  1585. return super().validators + [
  1586. validators.DecimalValidator(self.max_digits, self.decimal_places)
  1587. ]
  1588. @cached_property
  1589. def context(self):
  1590. return decimal.Context(prec=self.max_digits)
  1591. def deconstruct(self):
  1592. name, path, args, kwargs = super().deconstruct()
  1593. if self.max_digits is not None:
  1594. kwargs["max_digits"] = self.max_digits
  1595. if self.decimal_places is not None:
  1596. kwargs["decimal_places"] = self.decimal_places
  1597. return name, path, args, kwargs
  1598. def get_internal_type(self):
  1599. return "DecimalField"
  1600. def to_python(self, value):
  1601. if value is None:
  1602. return value
  1603. try:
  1604. if isinstance(value, float):
  1605. decimal_value = self.context.create_decimal_from_float(value)
  1606. else:
  1607. decimal_value = decimal.Decimal(value)
  1608. except (decimal.InvalidOperation, TypeError, ValueError):
  1609. raise exceptions.ValidationError(
  1610. self.error_messages["invalid"],
  1611. code="invalid",
  1612. params={"value": value},
  1613. )
  1614. if not decimal_value.is_finite():
  1615. raise exceptions.ValidationError(
  1616. self.error_messages["invalid"],
  1617. code="invalid",
  1618. params={"value": value},
  1619. )
  1620. return decimal_value
  1621. def get_db_prep_save(self, value, connection):
  1622. if hasattr(value, "as_sql"):
  1623. return value
  1624. return connection.ops.adapt_decimalfield_value(
  1625. self.to_python(value), self.max_digits, self.decimal_places
  1626. )
  1627. def get_prep_value(self, value):
  1628. value = super().get_prep_value(value)
  1629. return self.to_python(value)
  1630. def formfield(self, **kwargs):
  1631. return super().formfield(
  1632. **{
  1633. "max_digits": self.max_digits,
  1634. "decimal_places": self.decimal_places,
  1635. "form_class": forms.DecimalField,
  1636. **kwargs,
  1637. }
  1638. )
  1639. class DurationField(Field):
  1640. """
  1641. Store timedelta objects.
  1642. Use interval on PostgreSQL, INTERVAL DAY TO SECOND on Oracle, and bigint
  1643. of microseconds on other databases.
  1644. """
  1645. empty_strings_allowed = False
  1646. default_error_messages = {
  1647. "invalid": _(
  1648. "“%(value)s” value has an invalid format. It must be in "
  1649. "[DD] [[HH:]MM:]ss[.uuuuuu] format."
  1650. )
  1651. }
  1652. description = _("Duration")
  1653. def get_internal_type(self):
  1654. return "DurationField"
  1655. def to_python(self, value):
  1656. if value is None:
  1657. return value
  1658. if isinstance(value, datetime.timedelta):
  1659. return value
  1660. try:
  1661. parsed = parse_duration(value)
  1662. except ValueError:
  1663. pass
  1664. else:
  1665. if parsed is not None:
  1666. return parsed
  1667. raise exceptions.ValidationError(
  1668. self.error_messages["invalid"],
  1669. code="invalid",
  1670. params={"value": value},
  1671. )
  1672. def get_db_prep_value(self, value, connection, prepared=False):
  1673. if connection.features.has_native_duration_field:
  1674. return value
  1675. if value is None:
  1676. return None
  1677. return duration_microseconds(value)
  1678. def get_db_converters(self, connection):
  1679. converters = []
  1680. if not connection.features.has_native_duration_field:
  1681. converters.append(connection.ops.convert_durationfield_value)
  1682. return converters + super().get_db_converters(connection)
  1683. def value_to_string(self, obj):
  1684. val = self.value_from_object(obj)
  1685. return "" if val is None else duration_string(val)
  1686. def formfield(self, **kwargs):
  1687. return super().formfield(
  1688. **{
  1689. "form_class": forms.DurationField,
  1690. **kwargs,
  1691. }
  1692. )
  1693. class EmailField(CharField):
  1694. default_validators = [validators.validate_email]
  1695. description = _("Email address")
  1696. def __init__(self, *args, **kwargs):
  1697. # max_length=254 to be compliant with RFCs 3696 and 5321
  1698. kwargs.setdefault("max_length", 254)
  1699. super().__init__(*args, **kwargs)
  1700. def deconstruct(self):
  1701. name, path, args, kwargs = super().deconstruct()
  1702. # We do not exclude max_length if it matches default as we want to change
  1703. # the default in future.
  1704. return name, path, args, kwargs
  1705. def formfield(self, **kwargs):
  1706. # As with CharField, this will cause email validation to be performed
  1707. # twice.
  1708. return super().formfield(
  1709. **{
  1710. "form_class": forms.EmailField,
  1711. **kwargs,
  1712. }
  1713. )
  1714. class FilePathField(Field):
  1715. description = _("File path")
  1716. def __init__(
  1717. self,
  1718. verbose_name=None,
  1719. name=None,
  1720. path="",
  1721. match=None,
  1722. recursive=False,
  1723. allow_files=True,
  1724. allow_folders=False,
  1725. **kwargs,
  1726. ):
  1727. self.path, self.match, self.recursive = path, match, recursive
  1728. self.allow_files, self.allow_folders = allow_files, allow_folders
  1729. kwargs.setdefault("max_length", 100)
  1730. super().__init__(verbose_name, name, **kwargs)
  1731. def check(self, **kwargs):
  1732. return [
  1733. *super().check(**kwargs),
  1734. *self._check_allowing_files_or_folders(**kwargs),
  1735. ]
  1736. def _check_allowing_files_or_folders(self, **kwargs):
  1737. if not self.allow_files and not self.allow_folders:
  1738. return [
  1739. checks.Error(
  1740. "FilePathFields must have either 'allow_files' or 'allow_folders' "
  1741. "set to True.",
  1742. obj=self,
  1743. id="fields.E140",
  1744. )
  1745. ]
  1746. return []
  1747. def deconstruct(self):
  1748. name, path, args, kwargs = super().deconstruct()
  1749. if self.path != "":
  1750. kwargs["path"] = self.path
  1751. if self.match is not None:
  1752. kwargs["match"] = self.match
  1753. if self.recursive is not False:
  1754. kwargs["recursive"] = self.recursive
  1755. if self.allow_files is not True:
  1756. kwargs["allow_files"] = self.allow_files
  1757. if self.allow_folders is not False:
  1758. kwargs["allow_folders"] = self.allow_folders
  1759. if kwargs.get("max_length") == 100:
  1760. del kwargs["max_length"]
  1761. return name, path, args, kwargs
  1762. def get_prep_value(self, value):
  1763. value = super().get_prep_value(value)
  1764. if value is None:
  1765. return None
  1766. return str(value)
  1767. def formfield(self, **kwargs):
  1768. return super().formfield(
  1769. **{
  1770. "path": self.path() if callable(self.path) else self.path,
  1771. "match": self.match,
  1772. "recursive": self.recursive,
  1773. "form_class": forms.FilePathField,
  1774. "allow_files": self.allow_files,
  1775. "allow_folders": self.allow_folders,
  1776. **kwargs,
  1777. }
  1778. )
  1779. def get_internal_type(self):
  1780. return "FilePathField"
  1781. class FloatField(Field):
  1782. empty_strings_allowed = False
  1783. default_error_messages = {
  1784. "invalid": _("“%(value)s” value must be a float."),
  1785. }
  1786. description = _("Floating point number")
  1787. def get_prep_value(self, value):
  1788. value = super().get_prep_value(value)
  1789. if value is None:
  1790. return None
  1791. try:
  1792. return float(value)
  1793. except (TypeError, ValueError) as e:
  1794. raise e.__class__(
  1795. "Field '%s' expected a number but got %r." % (self.name, value),
  1796. ) from e
  1797. def get_internal_type(self):
  1798. return "FloatField"
  1799. def to_python(self, value):
  1800. if value is None:
  1801. return value
  1802. try:
  1803. return float(value)
  1804. except (TypeError, ValueError):
  1805. raise exceptions.ValidationError(
  1806. self.error_messages["invalid"],
  1807. code="invalid",
  1808. params={"value": value},
  1809. )
  1810. def formfield(self, **kwargs):
  1811. return super().formfield(
  1812. **{
  1813. "form_class": forms.FloatField,
  1814. **kwargs,
  1815. }
  1816. )
  1817. class IntegerField(Field):
  1818. empty_strings_allowed = False
  1819. default_error_messages = {
  1820. "invalid": _("“%(value)s” value must be an integer."),
  1821. }
  1822. description = _("Integer")
  1823. def check(self, **kwargs):
  1824. return [
  1825. *super().check(**kwargs),
  1826. *self._check_max_length_warning(),
  1827. ]
  1828. def _check_max_length_warning(self):
  1829. if self.max_length is not None:
  1830. return [
  1831. checks.Warning(
  1832. "'max_length' is ignored when used with %s."
  1833. % self.__class__.__name__,
  1834. hint="Remove 'max_length' from field",
  1835. obj=self,
  1836. id="fields.W122",
  1837. )
  1838. ]
  1839. return []
  1840. @cached_property
  1841. def validators(self):
  1842. # These validators can't be added at field initialization time since
  1843. # they're based on values retrieved from `connection`.
  1844. validators_ = super().validators
  1845. internal_type = self.get_internal_type()
  1846. min_value, max_value = connection.ops.integer_field_range(internal_type)
  1847. if min_value is not None and not any(
  1848. (
  1849. isinstance(validator, validators.MinValueValidator)
  1850. and (
  1851. validator.limit_value()
  1852. if callable(validator.limit_value)
  1853. else validator.limit_value
  1854. )
  1855. >= min_value
  1856. )
  1857. for validator in validators_
  1858. ):
  1859. validators_.append(validators.MinValueValidator(min_value))
  1860. if max_value is not None and not any(
  1861. (
  1862. isinstance(validator, validators.MaxValueValidator)
  1863. and (
  1864. validator.limit_value()
  1865. if callable(validator.limit_value)
  1866. else validator.limit_value
  1867. )
  1868. <= max_value
  1869. )
  1870. for validator in validators_
  1871. ):
  1872. validators_.append(validators.MaxValueValidator(max_value))
  1873. return validators_
  1874. def get_prep_value(self, value):
  1875. value = super().get_prep_value(value)
  1876. if value is None:
  1877. return None
  1878. try:
  1879. return int(value)
  1880. except (TypeError, ValueError) as e:
  1881. raise e.__class__(
  1882. "Field '%s' expected a number but got %r." % (self.name, value),
  1883. ) from e
  1884. def get_db_prep_value(self, value, connection, prepared=False):
  1885. value = super().get_db_prep_value(value, connection, prepared)
  1886. return connection.ops.adapt_integerfield_value(value, self.get_internal_type())
  1887. def get_internal_type(self):
  1888. return "IntegerField"
  1889. def to_python(self, value):
  1890. if value is None:
  1891. return value
  1892. try:
  1893. return int(value)
  1894. except (TypeError, ValueError):
  1895. raise exceptions.ValidationError(
  1896. self.error_messages["invalid"],
  1897. code="invalid",
  1898. params={"value": value},
  1899. )
  1900. def formfield(self, **kwargs):
  1901. return super().formfield(
  1902. **{
  1903. "form_class": forms.IntegerField,
  1904. **kwargs,
  1905. }
  1906. )
  1907. class BigIntegerField(IntegerField):
  1908. description = _("Big (8 byte) integer")
  1909. MAX_BIGINT = 9223372036854775807
  1910. def get_internal_type(self):
  1911. return "BigIntegerField"
  1912. def formfield(self, **kwargs):
  1913. return super().formfield(
  1914. **{
  1915. "min_value": -BigIntegerField.MAX_BIGINT - 1,
  1916. "max_value": BigIntegerField.MAX_BIGINT,
  1917. **kwargs,
  1918. }
  1919. )
  1920. class SmallIntegerField(IntegerField):
  1921. description = _("Small integer")
  1922. def get_internal_type(self):
  1923. return "SmallIntegerField"
  1924. class IPAddressField(Field):
  1925. empty_strings_allowed = False
  1926. description = _("IPv4 address")
  1927. system_check_removed_details = {
  1928. "msg": (
  1929. "IPAddressField has been removed except for support in "
  1930. "historical migrations."
  1931. ),
  1932. "hint": "Use GenericIPAddressField instead.",
  1933. "id": "fields.E900",
  1934. }
  1935. def __init__(self, *args, **kwargs):
  1936. kwargs["max_length"] = 15
  1937. super().__init__(*args, **kwargs)
  1938. def deconstruct(self):
  1939. name, path, args, kwargs = super().deconstruct()
  1940. del kwargs["max_length"]
  1941. return name, path, args, kwargs
  1942. def get_prep_value(self, value):
  1943. value = super().get_prep_value(value)
  1944. if value is None:
  1945. return None
  1946. return str(value)
  1947. def get_internal_type(self):
  1948. return "IPAddressField"
  1949. class GenericIPAddressField(Field):
  1950. empty_strings_allowed = False
  1951. description = _("IP address")
  1952. default_error_messages = {}
  1953. def __init__(
  1954. self,
  1955. verbose_name=None,
  1956. name=None,
  1957. protocol="both",
  1958. unpack_ipv4=False,
  1959. *args,
  1960. **kwargs,
  1961. ):
  1962. self.unpack_ipv4 = unpack_ipv4
  1963. self.protocol = protocol
  1964. (
  1965. self.default_validators,
  1966. invalid_error_message,
  1967. ) = validators.ip_address_validators(protocol, unpack_ipv4)
  1968. self.default_error_messages["invalid"] = invalid_error_message
  1969. kwargs["max_length"] = MAX_IPV6_ADDRESS_LENGTH
  1970. super().__init__(verbose_name, name, *args, **kwargs)
  1971. def check(self, **kwargs):
  1972. return [
  1973. *super().check(**kwargs),
  1974. *self._check_blank_and_null_values(**kwargs),
  1975. ]
  1976. def _check_blank_and_null_values(self, **kwargs):
  1977. if not getattr(self, "null", False) and getattr(self, "blank", False):
  1978. return [
  1979. checks.Error(
  1980. "GenericIPAddressFields cannot have blank=True if null=False, "
  1981. "as blank values are stored as nulls.",
  1982. obj=self,
  1983. id="fields.E150",
  1984. )
  1985. ]
  1986. return []
  1987. def deconstruct(self):
  1988. name, path, args, kwargs = super().deconstruct()
  1989. if self.unpack_ipv4 is not False:
  1990. kwargs["unpack_ipv4"] = self.unpack_ipv4
  1991. if self.protocol != "both":
  1992. kwargs["protocol"] = self.protocol
  1993. if kwargs.get("max_length") == self.max_length:
  1994. del kwargs["max_length"]
  1995. return name, path, args, kwargs
  1996. def get_internal_type(self):
  1997. return "GenericIPAddressField"
  1998. def to_python(self, value):
  1999. if value is None:
  2000. return None
  2001. if not isinstance(value, str):
  2002. value = str(value)
  2003. value = value.strip()
  2004. if ":" in value:
  2005. return clean_ipv6_address(
  2006. value, self.unpack_ipv4, self.error_messages["invalid"]
  2007. )
  2008. return value
  2009. def get_db_prep_value(self, value, connection, prepared=False):
  2010. if not prepared:
  2011. value = self.get_prep_value(value)
  2012. return connection.ops.adapt_ipaddressfield_value(value)
  2013. def get_prep_value(self, value):
  2014. value = super().get_prep_value(value)
  2015. if value is None:
  2016. return None
  2017. if value and ":" in value:
  2018. try:
  2019. return clean_ipv6_address(value, self.unpack_ipv4)
  2020. except exceptions.ValidationError:
  2021. pass
  2022. return str(value)
  2023. def formfield(self, **kwargs):
  2024. return super().formfield(
  2025. **{
  2026. "protocol": self.protocol,
  2027. "form_class": forms.GenericIPAddressField,
  2028. **kwargs,
  2029. }
  2030. )
  2031. class NullBooleanField(BooleanField):
  2032. default_error_messages = {
  2033. "invalid": _("“%(value)s” value must be either None, True or False."),
  2034. "invalid_nullable": _("“%(value)s” value must be either None, True or False."),
  2035. }
  2036. description = _("Boolean (Either True, False or None)")
  2037. system_check_removed_details = {
  2038. "msg": (
  2039. "NullBooleanField is removed except for support in historical "
  2040. "migrations."
  2041. ),
  2042. "hint": "Use BooleanField(null=True, blank=True) instead.",
  2043. "id": "fields.E903",
  2044. }
  2045. def __init__(self, *args, **kwargs):
  2046. kwargs["null"] = True
  2047. kwargs["blank"] = True
  2048. super().__init__(*args, **kwargs)
  2049. def deconstruct(self):
  2050. name, path, args, kwargs = super().deconstruct()
  2051. del kwargs["null"]
  2052. del kwargs["blank"]
  2053. return name, path, args, kwargs
  2054. class PositiveIntegerRelDbTypeMixin:
  2055. def __init_subclass__(cls, **kwargs):
  2056. super().__init_subclass__(**kwargs)
  2057. if not hasattr(cls, "integer_field_class"):
  2058. cls.integer_field_class = next(
  2059. (
  2060. parent
  2061. for parent in cls.__mro__[1:]
  2062. if issubclass(parent, IntegerField)
  2063. ),
  2064. None,
  2065. )
  2066. def rel_db_type(self, connection):
  2067. """
  2068. Return the data type that a related field pointing to this field should
  2069. use. In most cases, a foreign key pointing to a positive integer
  2070. primary key will have an integer column data type but some databases
  2071. (e.g. MySQL) have an unsigned integer type. In that case
  2072. (related_fields_match_type=True), the primary key should return its
  2073. db_type.
  2074. """
  2075. if connection.features.related_fields_match_type:
  2076. return self.db_type(connection)
  2077. else:
  2078. return self.integer_field_class().db_type(connection=connection)
  2079. class PositiveBigIntegerField(PositiveIntegerRelDbTypeMixin, BigIntegerField):
  2080. description = _("Positive big integer")
  2081. def get_internal_type(self):
  2082. return "PositiveBigIntegerField"
  2083. def formfield(self, **kwargs):
  2084. return super().formfield(
  2085. **{
  2086. "min_value": 0,
  2087. **kwargs,
  2088. }
  2089. )
  2090. class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField):
  2091. description = _("Positive integer")
  2092. def get_internal_type(self):
  2093. return "PositiveIntegerField"
  2094. def formfield(self, **kwargs):
  2095. return super().formfield(
  2096. **{
  2097. "min_value": 0,
  2098. **kwargs,
  2099. }
  2100. )
  2101. class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, SmallIntegerField):
  2102. description = _("Positive small integer")
  2103. def get_internal_type(self):
  2104. return "PositiveSmallIntegerField"
  2105. def formfield(self, **kwargs):
  2106. return super().formfield(
  2107. **{
  2108. "min_value": 0,
  2109. **kwargs,
  2110. }
  2111. )
  2112. class SlugField(CharField):
  2113. default_validators = [validators.validate_slug]
  2114. description = _("Slug (up to %(max_length)s)")
  2115. def __init__(
  2116. self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs
  2117. ):
  2118. self.allow_unicode = allow_unicode
  2119. if self.allow_unicode:
  2120. self.default_validators = [validators.validate_unicode_slug]
  2121. super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs)
  2122. def deconstruct(self):
  2123. name, path, args, kwargs = super().deconstruct()
  2124. if kwargs.get("max_length") == 50:
  2125. del kwargs["max_length"]
  2126. if self.db_index is False:
  2127. kwargs["db_index"] = False
  2128. else:
  2129. del kwargs["db_index"]
  2130. if self.allow_unicode is not False:
  2131. kwargs["allow_unicode"] = self.allow_unicode
  2132. return name, path, args, kwargs
  2133. def get_internal_type(self):
  2134. return "SlugField"
  2135. def formfield(self, **kwargs):
  2136. return super().formfield(
  2137. **{
  2138. "form_class": forms.SlugField,
  2139. "allow_unicode": self.allow_unicode,
  2140. **kwargs,
  2141. }
  2142. )
  2143. class TextField(Field):
  2144. description = _("Text")
  2145. def __init__(self, *args, db_collation=None, **kwargs):
  2146. super().__init__(*args, **kwargs)
  2147. self.db_collation = db_collation
  2148. def check(self, **kwargs):
  2149. databases = kwargs.get("databases") or []
  2150. return [
  2151. *super().check(**kwargs),
  2152. *self._check_db_collation(databases),
  2153. ]
  2154. def _check_db_collation(self, databases):
  2155. errors = []
  2156. for db in databases:
  2157. if not router.allow_migrate_model(db, self.model):
  2158. continue
  2159. connection = connections[db]
  2160. if not (
  2161. self.db_collation is None
  2162. or "supports_collation_on_textfield"
  2163. in self.model._meta.required_db_features
  2164. or connection.features.supports_collation_on_textfield
  2165. ):
  2166. errors.append(
  2167. checks.Error(
  2168. "%s does not support a database collation on "
  2169. "TextFields." % connection.display_name,
  2170. obj=self,
  2171. id="fields.E190",
  2172. ),
  2173. )
  2174. return errors
  2175. def db_parameters(self, connection):
  2176. db_params = super().db_parameters(connection)
  2177. db_params["collation"] = self.db_collation
  2178. return db_params
  2179. def get_internal_type(self):
  2180. return "TextField"
  2181. def to_python(self, value):
  2182. if isinstance(value, str) or value is None:
  2183. return value
  2184. return str(value)
  2185. def get_prep_value(self, value):
  2186. value = super().get_prep_value(value)
  2187. return self.to_python(value)
  2188. def formfield(self, **kwargs):
  2189. # Passing max_length to forms.CharField means that the value's length
  2190. # will be validated twice. This is considered acceptable since we want
  2191. # the value in the form field (to pass into widget for example).
  2192. return super().formfield(
  2193. **{
  2194. "max_length": self.max_length,
  2195. **({} if self.choices is not None else {"widget": forms.Textarea}),
  2196. **kwargs,
  2197. }
  2198. )
  2199. def deconstruct(self):
  2200. name, path, args, kwargs = super().deconstruct()
  2201. if self.db_collation:
  2202. kwargs["db_collation"] = self.db_collation
  2203. return name, path, args, kwargs
  2204. class TimeField(DateTimeCheckMixin, Field):
  2205. empty_strings_allowed = False
  2206. default_error_messages = {
  2207. "invalid": _(
  2208. "“%(value)s” value has an invalid format. It must be in "
  2209. "HH:MM[:ss[.uuuuuu]] format."
  2210. ),
  2211. "invalid_time": _(
  2212. "“%(value)s” value has the correct format "
  2213. "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."
  2214. ),
  2215. }
  2216. description = _("Time")
  2217. def __init__(
  2218. self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs
  2219. ):
  2220. self.auto_now, self.auto_now_add = auto_now, auto_now_add
  2221. if auto_now or auto_now_add:
  2222. kwargs["editable"] = False
  2223. kwargs["blank"] = True
  2224. super().__init__(verbose_name, name, **kwargs)
  2225. def _check_fix_default_value(self):
  2226. """
  2227. Warn that using an actual date or datetime value is probably wrong;
  2228. it's only evaluated on server startup.
  2229. """
  2230. if not self.has_default():
  2231. return []
  2232. value = self.default
  2233. if isinstance(value, datetime.datetime):
  2234. now = None
  2235. elif isinstance(value, datetime.time):
  2236. now = _get_naive_now()
  2237. # This will not use the right date in the race condition where now
  2238. # is just before the date change and value is just past 0:00.
  2239. value = datetime.datetime.combine(now.date(), value)
  2240. else:
  2241. # No explicit time / datetime value -- no checks necessary
  2242. return []
  2243. # At this point, value is a datetime object.
  2244. return self._check_if_value_fixed(value, now=now)
  2245. def deconstruct(self):
  2246. name, path, args, kwargs = super().deconstruct()
  2247. if self.auto_now is not False:
  2248. kwargs["auto_now"] = self.auto_now
  2249. if self.auto_now_add is not False:
  2250. kwargs["auto_now_add"] = self.auto_now_add
  2251. if self.auto_now or self.auto_now_add:
  2252. del kwargs["blank"]
  2253. del kwargs["editable"]
  2254. return name, path, args, kwargs
  2255. def get_internal_type(self):
  2256. return "TimeField"
  2257. def to_python(self, value):
  2258. if value is None:
  2259. return None
  2260. if isinstance(value, datetime.time):
  2261. return value
  2262. if isinstance(value, datetime.datetime):
  2263. # Not usually a good idea to pass in a datetime here (it loses
  2264. # information), but this can be a side-effect of interacting with a
  2265. # database backend (e.g. Oracle), so we'll be accommodating.
  2266. return value.time()
  2267. try:
  2268. parsed = parse_time(value)
  2269. if parsed is not None:
  2270. return parsed
  2271. except ValueError:
  2272. raise exceptions.ValidationError(
  2273. self.error_messages["invalid_time"],
  2274. code="invalid_time",
  2275. params={"value": value},
  2276. )
  2277. raise exceptions.ValidationError(
  2278. self.error_messages["invalid"],
  2279. code="invalid",
  2280. params={"value": value},
  2281. )
  2282. def pre_save(self, model_instance, add):
  2283. if self.auto_now or (self.auto_now_add and add):
  2284. value = datetime.datetime.now().time()
  2285. setattr(model_instance, self.attname, value)
  2286. return value
  2287. else:
  2288. return super().pre_save(model_instance, add)
  2289. def get_prep_value(self, value):
  2290. value = super().get_prep_value(value)
  2291. return self.to_python(value)
  2292. def get_db_prep_value(self, value, connection, prepared=False):
  2293. # Casts times into the format expected by the backend
  2294. if not prepared:
  2295. value = self.get_prep_value(value)
  2296. return connection.ops.adapt_timefield_value(value)
  2297. def value_to_string(self, obj):
  2298. val = self.value_from_object(obj)
  2299. return "" if val is None else val.isoformat()
  2300. def formfield(self, **kwargs):
  2301. return super().formfield(
  2302. **{
  2303. "form_class": forms.TimeField,
  2304. **kwargs,
  2305. }
  2306. )
  2307. class URLField(CharField):
  2308. default_validators = [validators.URLValidator()]
  2309. description = _("URL")
  2310. def __init__(self, verbose_name=None, name=None, **kwargs):
  2311. kwargs.setdefault("max_length", 200)
  2312. super().__init__(verbose_name, name, **kwargs)
  2313. def deconstruct(self):
  2314. name, path, args, kwargs = super().deconstruct()
  2315. if kwargs.get("max_length") == 200:
  2316. del kwargs["max_length"]
  2317. return name, path, args, kwargs
  2318. def formfield(self, **kwargs):
  2319. # As with CharField, this will cause URL validation to be performed
  2320. # twice.
  2321. return super().formfield(
  2322. **{
  2323. "form_class": forms.URLField,
  2324. **kwargs,
  2325. }
  2326. )
  2327. class BinaryField(Field):
  2328. description = _("Raw binary data")
  2329. empty_values = [None, b""]
  2330. def __init__(self, *args, **kwargs):
  2331. kwargs.setdefault("editable", False)
  2332. super().__init__(*args, **kwargs)
  2333. if self.max_length is not None:
  2334. self.validators.append(validators.MaxLengthValidator(self.max_length))
  2335. def check(self, **kwargs):
  2336. return [*super().check(**kwargs), *self._check_str_default_value()]
  2337. def _check_str_default_value(self):
  2338. if self.has_default() and isinstance(self.default, str):
  2339. return [
  2340. checks.Error(
  2341. "BinaryField's default cannot be a string. Use bytes "
  2342. "content instead.",
  2343. obj=self,
  2344. id="fields.E170",
  2345. )
  2346. ]
  2347. return []
  2348. def deconstruct(self):
  2349. name, path, args, kwargs = super().deconstruct()
  2350. if self.editable:
  2351. kwargs["editable"] = True
  2352. else:
  2353. del kwargs["editable"]
  2354. return name, path, args, kwargs
  2355. def get_internal_type(self):
  2356. return "BinaryField"
  2357. def get_placeholder(self, value, compiler, connection):
  2358. return connection.ops.binary_placeholder_sql(value)
  2359. def get_default(self):
  2360. if self.has_default() and not callable(self.default):
  2361. return self.default
  2362. default = super().get_default()
  2363. if default == "":
  2364. return b""
  2365. return default
  2366. def get_db_prep_value(self, value, connection, prepared=False):
  2367. value = super().get_db_prep_value(value, connection, prepared)
  2368. if value is not None:
  2369. return connection.Database.Binary(value)
  2370. return value
  2371. def value_to_string(self, obj):
  2372. """Binary data is serialized as base64"""
  2373. return b64encode(self.value_from_object(obj)).decode("ascii")
  2374. def to_python(self, value):
  2375. # If it's a string, it should be base64-encoded data
  2376. if isinstance(value, str):
  2377. return memoryview(b64decode(value.encode("ascii")))
  2378. return value
  2379. class UUIDField(Field):
  2380. default_error_messages = {
  2381. "invalid": _("“%(value)s” is not a valid UUID."),
  2382. }
  2383. description = _("Universally unique identifier")
  2384. empty_strings_allowed = False
  2385. def __init__(self, verbose_name=None, **kwargs):
  2386. kwargs["max_length"] = 32
  2387. super().__init__(verbose_name, **kwargs)
  2388. def deconstruct(self):
  2389. name, path, args, kwargs = super().deconstruct()
  2390. del kwargs["max_length"]
  2391. return name, path, args, kwargs
  2392. def get_internal_type(self):
  2393. return "UUIDField"
  2394. def get_prep_value(self, value):
  2395. value = super().get_prep_value(value)
  2396. return self.to_python(value)
  2397. def get_db_prep_value(self, value, connection, prepared=False):
  2398. if value is None:
  2399. return None
  2400. if not isinstance(value, uuid.UUID):
  2401. value = self.to_python(value)
  2402. if connection.features.has_native_uuid_field:
  2403. return value
  2404. return value.hex
  2405. def to_python(self, value):
  2406. if value is not None and not isinstance(value, uuid.UUID):
  2407. input_form = "int" if isinstance(value, int) else "hex"
  2408. try:
  2409. return uuid.UUID(**{input_form: value})
  2410. except (AttributeError, ValueError):
  2411. raise exceptions.ValidationError(
  2412. self.error_messages["invalid"],
  2413. code="invalid",
  2414. params={"value": value},
  2415. )
  2416. return value
  2417. def formfield(self, **kwargs):
  2418. return super().formfield(
  2419. **{
  2420. "form_class": forms.UUIDField,
  2421. **kwargs,
  2422. }
  2423. )
  2424. class AutoFieldMixin:
  2425. db_returning = True
  2426. def __init__(self, *args, **kwargs):
  2427. kwargs["blank"] = True
  2428. super().__init__(*args, **kwargs)
  2429. def check(self, **kwargs):
  2430. return [
  2431. *super().check(**kwargs),
  2432. *self._check_primary_key(),
  2433. ]
  2434. def _check_primary_key(self):
  2435. if not self.primary_key:
  2436. return [
  2437. checks.Error(
  2438. "AutoFields must set primary_key=True.",
  2439. obj=self,
  2440. id="fields.E100",
  2441. ),
  2442. ]
  2443. else:
  2444. return []
  2445. def deconstruct(self):
  2446. name, path, args, kwargs = super().deconstruct()
  2447. del kwargs["blank"]
  2448. kwargs["primary_key"] = True
  2449. return name, path, args, kwargs
  2450. def validate(self, value, model_instance):
  2451. pass
  2452. def get_db_prep_value(self, value, connection, prepared=False):
  2453. if not prepared:
  2454. value = self.get_prep_value(value)
  2455. value = connection.ops.validate_autopk_value(value)
  2456. return value
  2457. def contribute_to_class(self, cls, name, **kwargs):
  2458. if cls._meta.auto_field:
  2459. raise ValueError(
  2460. "Model %s can't have more than one auto-generated field."
  2461. % cls._meta.label
  2462. )
  2463. super().contribute_to_class(cls, name, **kwargs)
  2464. cls._meta.auto_field = self
  2465. def formfield(self, **kwargs):
  2466. return None
  2467. class AutoFieldMeta(type):
  2468. """
  2469. Metaclass to maintain backward inheritance compatibility for AutoField.
  2470. It is intended that AutoFieldMixin become public API when it is possible to
  2471. create a non-integer automatically-generated field using column defaults
  2472. stored in the database.
  2473. In many areas Django also relies on using isinstance() to check for an
  2474. automatically-generated field as a subclass of AutoField. A new flag needs
  2475. to be implemented on Field to be used instead.
  2476. When these issues have been addressed, this metaclass could be used to
  2477. deprecate inheritance from AutoField and use of isinstance() with AutoField
  2478. for detecting automatically-generated fields.
  2479. """
  2480. @property
  2481. def _subclasses(self):
  2482. return (BigAutoField, SmallAutoField)
  2483. def __instancecheck__(self, instance):
  2484. return isinstance(instance, self._subclasses) or super().__instancecheck__(
  2485. instance
  2486. )
  2487. def __subclasscheck__(self, subclass):
  2488. return issubclass(subclass, self._subclasses) or super().__subclasscheck__(
  2489. subclass
  2490. )
  2491. class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta):
  2492. def get_internal_type(self):
  2493. return "AutoField"
  2494. def rel_db_type(self, connection):
  2495. return IntegerField().db_type(connection=connection)
  2496. class BigAutoField(AutoFieldMixin, BigIntegerField):
  2497. def get_internal_type(self):
  2498. return "BigAutoField"
  2499. def rel_db_type(self, connection):
  2500. return BigIntegerField().db_type(connection=connection)
  2501. class SmallAutoField(AutoFieldMixin, SmallIntegerField):
  2502. def get_internal_type(self):
  2503. return "SmallAutoField"
  2504. def rel_db_type(self, connection):
  2505. return SmallIntegerField().db_type(connection=connection)