base.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. from __future__ import unicode_literals
  2. import copy
  3. import sys
  4. from functools import update_wrapper
  5. import warnings
  6. from django.apps import apps
  7. from django.apps.config import MODELS_MODULE_NAME
  8. import django.db.models.manager # NOQA: Imported to register signal handler.
  9. from django.conf import settings
  10. from django.core import checks
  11. from django.core.exceptions import (ObjectDoesNotExist,
  12. MultipleObjectsReturned, FieldError, ValidationError, NON_FIELD_ERRORS)
  13. from django.db.models.fields import AutoField, FieldDoesNotExist
  14. from django.db.models.fields.related import (ForeignObjectRel, ManyToOneRel,
  15. OneToOneField, add_lazy_relation)
  16. from django.db import (router, transaction, DatabaseError,
  17. DEFAULT_DB_ALIAS)
  18. from django.db.models.query import Q
  19. from django.db.models.query_utils import DeferredAttribute, deferred_class_factory
  20. from django.db.models.deletion import Collector
  21. from django.db.models.options import Options
  22. from django.db.models import signals
  23. from django.utils import six
  24. from django.utils.deprecation import RemovedInDjango19Warning
  25. from django.utils.encoding import force_str, force_text
  26. from django.utils.functional import curry
  27. from django.utils.six.moves import zip
  28. from django.utils.text import get_text_list, capfirst
  29. from django.utils.translation import ugettext_lazy as _
  30. def subclass_exception(name, parents, module, attached_to=None):
  31. """
  32. Create exception subclass. Used by ModelBase below.
  33. If 'attached_to' is supplied, the exception will be created in a way that
  34. allows it to be pickled, assuming the returned exception class will be added
  35. as an attribute to the 'attached_to' class.
  36. """
  37. class_dict = {'__module__': module}
  38. if attached_to is not None:
  39. def __reduce__(self):
  40. # Exceptions are special - they've got state that isn't
  41. # in self.__dict__. We assume it is all in self.args.
  42. return (unpickle_inner_exception, (attached_to, name), self.args)
  43. def __setstate__(self, args):
  44. self.args = args
  45. class_dict['__reduce__'] = __reduce__
  46. class_dict['__setstate__'] = __setstate__
  47. return type(name, parents, class_dict)
  48. class ModelBase(type):
  49. """
  50. Metaclass for all models.
  51. """
  52. def __new__(cls, name, bases, attrs):
  53. super_new = super(ModelBase, cls).__new__
  54. # Also ensure initialization is only performed for subclasses of Model
  55. # (excluding Model class itself).
  56. parents = [b for b in bases if isinstance(b, ModelBase)]
  57. if not parents:
  58. return super_new(cls, name, bases, attrs)
  59. # Create the class.
  60. module = attrs.pop('__module__')
  61. new_class = super_new(cls, name, bases, {'__module__': module})
  62. attr_meta = attrs.pop('Meta', None)
  63. abstract = getattr(attr_meta, 'abstract', False)
  64. if not attr_meta:
  65. meta = getattr(new_class, 'Meta', None)
  66. else:
  67. meta = attr_meta
  68. base_meta = getattr(new_class, '_meta', None)
  69. # Look for an application configuration to attach the model to.
  70. app_config = apps.get_containing_app_config(module)
  71. if getattr(meta, 'app_label', None) is None:
  72. if app_config is None:
  73. # If the model is imported before the configuration for its
  74. # application is created (#21719), or isn't in an installed
  75. # application (#21680), use the legacy logic to figure out the
  76. # app_label by looking one level up from the package or module
  77. # named 'models'. If no such package or module exists, fall
  78. # back to looking one level up from the module this model is
  79. # defined in.
  80. # For 'django.contrib.sites.models', this would be 'sites'.
  81. # For 'geo.models.places' this would be 'geo'.
  82. msg = (
  83. "Model class %s.%s doesn't declare an explicit app_label "
  84. "and either isn't in an application in INSTALLED_APPS or "
  85. "else was imported before its application was loaded. " %
  86. (module, name))
  87. if abstract:
  88. msg += "Its app_label will be set to None in Django 1.9."
  89. else:
  90. msg += "This will no longer be supported in Django 1.9."
  91. warnings.warn(msg, RemovedInDjango19Warning, stacklevel=2)
  92. model_module = sys.modules[new_class.__module__]
  93. package_components = model_module.__name__.split('.')
  94. package_components.reverse() # find the last occurrence of 'models'
  95. try:
  96. app_label_index = package_components.index(MODELS_MODULE_NAME) + 1
  97. except ValueError:
  98. app_label_index = 1
  99. kwargs = {"app_label": package_components[app_label_index]}
  100. else:
  101. kwargs = {"app_label": app_config.label}
  102. else:
  103. kwargs = {}
  104. new_class.add_to_class('_meta', Options(meta, **kwargs))
  105. if not abstract:
  106. new_class.add_to_class(
  107. 'DoesNotExist',
  108. subclass_exception(
  109. str('DoesNotExist'),
  110. tuple(x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (ObjectDoesNotExist,),
  111. module,
  112. attached_to=new_class))
  113. new_class.add_to_class(
  114. 'MultipleObjectsReturned',
  115. subclass_exception(
  116. str('MultipleObjectsReturned'),
  117. tuple(x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (MultipleObjectsReturned,),
  118. module,
  119. attached_to=new_class))
  120. if base_meta and not base_meta.abstract:
  121. # Non-abstract child classes inherit some attributes from their
  122. # non-abstract parent (unless an ABC comes before it in the
  123. # method resolution order).
  124. if not hasattr(meta, 'ordering'):
  125. new_class._meta.ordering = base_meta.ordering
  126. if not hasattr(meta, 'get_latest_by'):
  127. new_class._meta.get_latest_by = base_meta.get_latest_by
  128. is_proxy = new_class._meta.proxy
  129. # If the model is a proxy, ensure that the base class
  130. # hasn't been swapped out.
  131. if is_proxy and base_meta and base_meta.swapped:
  132. raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped))
  133. if getattr(new_class, '_default_manager', None):
  134. if not is_proxy:
  135. # Multi-table inheritance doesn't inherit default manager from
  136. # parents.
  137. new_class._default_manager = None
  138. new_class._base_manager = None
  139. else:
  140. # Proxy classes do inherit parent's default manager, if none is
  141. # set explicitly.
  142. new_class._default_manager = new_class._default_manager._copy_to_model(new_class)
  143. new_class._base_manager = new_class._base_manager._copy_to_model(new_class)
  144. # Add all attributes to the class.
  145. for obj_name, obj in attrs.items():
  146. new_class.add_to_class(obj_name, obj)
  147. # All the fields of any type declared on this model
  148. new_fields = (
  149. new_class._meta.local_fields +
  150. new_class._meta.local_many_to_many +
  151. new_class._meta.virtual_fields
  152. )
  153. field_names = set(f.name for f in new_fields)
  154. # Basic setup for proxy models.
  155. if is_proxy:
  156. base = None
  157. for parent in [kls for kls in parents if hasattr(kls, '_meta')]:
  158. if parent._meta.abstract:
  159. if parent._meta.fields:
  160. raise TypeError("Abstract base class containing model fields not permitted for proxy model '%s'." % name)
  161. else:
  162. continue
  163. if base is not None:
  164. raise TypeError("Proxy model '%s' has more than one non-abstract model base class." % name)
  165. else:
  166. base = parent
  167. if base is None:
  168. raise TypeError("Proxy model '%s' has no non-abstract model base class." % name)
  169. new_class._meta.setup_proxy(base)
  170. new_class._meta.concrete_model = base._meta.concrete_model
  171. else:
  172. new_class._meta.concrete_model = new_class
  173. # Collect the parent links for multi-table inheritance.
  174. parent_links = {}
  175. for base in reversed([new_class] + parents):
  176. # Conceptually equivalent to `if base is Model`.
  177. if not hasattr(base, '_meta'):
  178. continue
  179. # Skip concrete parent classes.
  180. if base != new_class and not base._meta.abstract:
  181. continue
  182. # Locate OneToOneField instances.
  183. for field in base._meta.local_fields:
  184. if isinstance(field, OneToOneField):
  185. parent_links[field.rel.to] = field
  186. # Do the appropriate setup for any model parents.
  187. for base in parents:
  188. original_base = base
  189. if not hasattr(base, '_meta'):
  190. # Things without _meta aren't functional models, so they're
  191. # uninteresting parents.
  192. continue
  193. parent_fields = base._meta.local_fields + base._meta.local_many_to_many
  194. # Check for clashes between locally declared fields and those
  195. # on the base classes (we cannot handle shadowed fields at the
  196. # moment).
  197. for field in parent_fields:
  198. if field.name in field_names:
  199. raise FieldError(
  200. 'Local field %r in class %r clashes '
  201. 'with field of similar name from '
  202. 'base class %r' % (field.name, name, base.__name__)
  203. )
  204. if not base._meta.abstract:
  205. # Concrete classes...
  206. base = base._meta.concrete_model
  207. if base in parent_links:
  208. field = parent_links[base]
  209. elif not is_proxy:
  210. attr_name = '%s_ptr' % base._meta.model_name
  211. field = OneToOneField(base, name=attr_name,
  212. auto_created=True, parent_link=True)
  213. # Only add the ptr field if it's not already present;
  214. # e.g. migrations will already have it specified
  215. if not hasattr(new_class, attr_name):
  216. new_class.add_to_class(attr_name, field)
  217. else:
  218. field = None
  219. new_class._meta.parents[base] = field
  220. else:
  221. # .. and abstract ones.
  222. for field in parent_fields:
  223. new_class.add_to_class(field.name, copy.deepcopy(field))
  224. # Pass any non-abstract parent classes onto child.
  225. new_class._meta.parents.update(base._meta.parents)
  226. # Inherit managers from the abstract base classes.
  227. new_class.copy_managers(base._meta.abstract_managers)
  228. # Proxy models inherit the non-abstract managers from their base,
  229. # unless they have redefined any of them.
  230. if is_proxy:
  231. new_class.copy_managers(original_base._meta.concrete_managers)
  232. # Inherit virtual fields (like GenericForeignKey) from the parent
  233. # class
  234. for field in base._meta.virtual_fields:
  235. if base._meta.abstract and field.name in field_names:
  236. raise FieldError(
  237. 'Local field %r in class %r clashes '
  238. 'with field of similar name from '
  239. 'abstract base class %r' % (field.name, name, base.__name__)
  240. )
  241. new_class.add_to_class(field.name, copy.deepcopy(field))
  242. if abstract:
  243. # Abstract base models can't be instantiated and don't appear in
  244. # the list of models for an app. We do the final setup for them a
  245. # little differently from normal models.
  246. attr_meta.abstract = False
  247. new_class.Meta = attr_meta
  248. return new_class
  249. new_class._prepare()
  250. new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
  251. return new_class
  252. def copy_managers(cls, base_managers):
  253. # This is in-place sorting of an Options attribute, but that's fine.
  254. base_managers.sort()
  255. for _, mgr_name, manager in base_managers: # NOQA (redefinition of _)
  256. val = getattr(cls, mgr_name, None)
  257. if not val or val is manager:
  258. new_manager = manager._copy_to_model(cls)
  259. cls.add_to_class(mgr_name, new_manager)
  260. def add_to_class(cls, name, value):
  261. if hasattr(value, 'contribute_to_class'):
  262. value.contribute_to_class(cls, name)
  263. else:
  264. setattr(cls, name, value)
  265. def _prepare(cls):
  266. """
  267. Creates some methods once self._meta has been populated.
  268. """
  269. opts = cls._meta
  270. opts._prepare(cls)
  271. if opts.order_with_respect_to:
  272. cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True)
  273. cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False)
  274. # defer creating accessors on the foreign class until we are
  275. # certain it has been created
  276. def make_foreign_order_accessors(field, model, cls):
  277. setattr(
  278. field.rel.to,
  279. 'get_%s_order' % cls.__name__.lower(),
  280. curry(method_get_order, cls)
  281. )
  282. setattr(
  283. field.rel.to,
  284. 'set_%s_order' % cls.__name__.lower(),
  285. curry(method_set_order, cls)
  286. )
  287. add_lazy_relation(
  288. cls,
  289. opts.order_with_respect_to,
  290. opts.order_with_respect_to.rel.to,
  291. make_foreign_order_accessors
  292. )
  293. # Give the class a docstring -- its definition.
  294. if cls.__doc__ is None:
  295. cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join(f.attname for f in opts.fields))
  296. if hasattr(cls, 'get_absolute_url'):
  297. cls.get_absolute_url = update_wrapper(curry(get_absolute_url, opts, cls.get_absolute_url),
  298. cls.get_absolute_url)
  299. signals.class_prepared.send(sender=cls)
  300. class ModelState(object):
  301. """
  302. A class for storing instance state
  303. """
  304. def __init__(self, db=None):
  305. self.db = db
  306. # If true, uniqueness validation checks will consider this a new, as-yet-unsaved object.
  307. # Necessary for correct validation of new instances of objects with explicit (non-auto) PKs.
  308. # This impacts validation only; it has no effect on the actual save.
  309. self.adding = True
  310. class Model(six.with_metaclass(ModelBase)):
  311. _deferred = False
  312. def __init__(self, *args, **kwargs):
  313. signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
  314. # Set up the storage for instance state
  315. self._state = ModelState()
  316. # There is a rather weird disparity here; if kwargs, it's set, then args
  317. # overrides it. It should be one or the other; don't duplicate the work
  318. # The reason for the kwargs check is that standard iterator passes in by
  319. # args, and instantiation for iteration is 33% faster.
  320. args_len = len(args)
  321. if args_len > len(self._meta.concrete_fields):
  322. # Daft, but matches old exception sans the err msg.
  323. raise IndexError("Number of args exceeds number of fields")
  324. if not kwargs:
  325. fields_iter = iter(self._meta.concrete_fields)
  326. # The ordering of the zip calls matter - zip throws StopIteration
  327. # when an iter throws it. So if the first iter throws it, the second
  328. # is *not* consumed. We rely on this, so don't change the order
  329. # without changing the logic.
  330. for val, field in zip(args, fields_iter):
  331. setattr(self, field.attname, val)
  332. else:
  333. # Slower, kwargs-ready version.
  334. fields_iter = iter(self._meta.fields)
  335. for val, field in zip(args, fields_iter):
  336. setattr(self, field.attname, val)
  337. kwargs.pop(field.name, None)
  338. # Maintain compatibility with existing calls.
  339. if isinstance(field.rel, ManyToOneRel):
  340. kwargs.pop(field.attname, None)
  341. # Now we're left with the unprocessed fields that *must* come from
  342. # keywords, or default.
  343. for field in fields_iter:
  344. is_related_object = False
  345. # This slightly odd construct is so that we can access any
  346. # data-descriptor object (DeferredAttribute) without triggering its
  347. # __get__ method.
  348. if (field.attname not in kwargs and
  349. (isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)
  350. or field.column is None)):
  351. # This field will be populated on request.
  352. continue
  353. if kwargs:
  354. if isinstance(field.rel, ForeignObjectRel):
  355. try:
  356. # Assume object instance was passed in.
  357. rel_obj = kwargs.pop(field.name)
  358. is_related_object = True
  359. except KeyError:
  360. try:
  361. # Object instance wasn't passed in -- must be an ID.
  362. val = kwargs.pop(field.attname)
  363. except KeyError:
  364. val = field.get_default()
  365. else:
  366. # Object instance was passed in. Special case: You can
  367. # pass in "None" for related objects if it's allowed.
  368. if rel_obj is None and field.null:
  369. val = None
  370. else:
  371. try:
  372. val = kwargs.pop(field.attname)
  373. except KeyError:
  374. # This is done with an exception rather than the
  375. # default argument on pop because we don't want
  376. # get_default() to be evaluated, and then not used.
  377. # Refs #12057.
  378. val = field.get_default()
  379. else:
  380. val = field.get_default()
  381. if is_related_object:
  382. # If we are passed a related instance, set it using the
  383. # field.name instead of field.attname (e.g. "user" instead of
  384. # "user_id") so that the object gets properly cached (and type
  385. # checked) by the RelatedObjectDescriptor.
  386. setattr(self, field.name, rel_obj)
  387. else:
  388. setattr(self, field.attname, val)
  389. if kwargs:
  390. for prop in list(kwargs):
  391. try:
  392. if isinstance(getattr(self.__class__, prop), property):
  393. setattr(self, prop, kwargs.pop(prop))
  394. except AttributeError:
  395. pass
  396. if kwargs:
  397. raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
  398. super(Model, self).__init__()
  399. signals.post_init.send(sender=self.__class__, instance=self)
  400. def __repr__(self):
  401. try:
  402. u = six.text_type(self)
  403. except (UnicodeEncodeError, UnicodeDecodeError):
  404. u = '[Bad Unicode data]'
  405. return force_str('<%s: %s>' % (self.__class__.__name__, u))
  406. def __str__(self):
  407. if six.PY2 and hasattr(self, '__unicode__'):
  408. return force_text(self).encode('utf-8')
  409. return '%s object' % self.__class__.__name__
  410. def __eq__(self, other):
  411. if not isinstance(other, Model):
  412. return False
  413. if self._meta.concrete_model != other._meta.concrete_model:
  414. return False
  415. my_pk = self._get_pk_val()
  416. if my_pk is None:
  417. return self is other
  418. return my_pk == other._get_pk_val()
  419. def __ne__(self, other):
  420. return not self.__eq__(other)
  421. def __hash__(self):
  422. if self._get_pk_val() is None:
  423. raise TypeError("Model instances without primary key value are unhashable")
  424. return hash(self._get_pk_val())
  425. def __reduce__(self):
  426. """
  427. Provides pickling support. Normally, this just dispatches to Python's
  428. standard handling. However, for models with deferred field loading, we
  429. need to do things manually, as they're dynamically created classes and
  430. only module-level classes can be pickled by the default path.
  431. """
  432. data = self.__dict__
  433. if not self._deferred:
  434. class_id = self._meta.app_label, self._meta.object_name
  435. return model_unpickle, (class_id, [], simple_class_factory), data
  436. defers = []
  437. for field in self._meta.fields:
  438. if isinstance(self.__class__.__dict__.get(field.attname),
  439. DeferredAttribute):
  440. defers.append(field.attname)
  441. model = self._meta.proxy_for_model
  442. class_id = model._meta.app_label, model._meta.object_name
  443. return (model_unpickle, (class_id, defers, deferred_class_factory), data)
  444. def _get_pk_val(self, meta=None):
  445. if not meta:
  446. meta = self._meta
  447. return getattr(self, meta.pk.attname)
  448. def _set_pk_val(self, value):
  449. return setattr(self, self._meta.pk.attname, value)
  450. pk = property(_get_pk_val, _set_pk_val)
  451. def serializable_value(self, field_name):
  452. """
  453. Returns the value of the field name for this instance. If the field is
  454. a foreign key, returns the id value, instead of the object. If there's
  455. no Field object with this name on the model, the model attribute's
  456. value is returned directly.
  457. Used to serialize a field's value (in the serializer, or form output,
  458. for example). Normally, you would just access the attribute directly
  459. and not use this method.
  460. """
  461. try:
  462. field = self._meta.get_field_by_name(field_name)[0]
  463. except FieldDoesNotExist:
  464. return getattr(self, field_name)
  465. return getattr(self, field.attname)
  466. def save(self, force_insert=False, force_update=False, using=None,
  467. update_fields=None):
  468. """
  469. Saves the current instance. Override this in a subclass if you want to
  470. control the saving process.
  471. The 'force_insert' and 'force_update' parameters can be used to insist
  472. that the "save" must be an SQL insert or update (or equivalent for
  473. non-SQL backends), respectively. Normally, they should not be set.
  474. """
  475. using = using or router.db_for_write(self.__class__, instance=self)
  476. if force_insert and (force_update or update_fields):
  477. raise ValueError("Cannot force both insert and updating in model saving.")
  478. if update_fields is not None:
  479. # If update_fields is empty, skip the save. We do also check for
  480. # no-op saves later on for inheritance cases. This bailout is
  481. # still needed for skipping signal sending.
  482. if len(update_fields) == 0:
  483. return
  484. update_fields = frozenset(update_fields)
  485. field_names = set()
  486. for field in self._meta.fields:
  487. if not field.primary_key:
  488. field_names.add(field.name)
  489. if field.name != field.attname:
  490. field_names.add(field.attname)
  491. non_model_fields = update_fields.difference(field_names)
  492. if non_model_fields:
  493. raise ValueError("The following fields do not exist in this "
  494. "model or are m2m fields: %s"
  495. % ', '.join(non_model_fields))
  496. # If saving to the same database, and this model is deferred, then
  497. # automatically do a "update_fields" save on the loaded fields.
  498. elif not force_insert and self._deferred and using == self._state.db:
  499. field_names = set()
  500. for field in self._meta.concrete_fields:
  501. if not field.primary_key and not hasattr(field, 'through'):
  502. field_names.add(field.attname)
  503. deferred_fields = [
  504. f.attname for f in self._meta.fields
  505. if (f.attname not in self.__dict__ and
  506. isinstance(self.__class__.__dict__[f.attname], DeferredAttribute))
  507. ]
  508. loaded_fields = field_names.difference(deferred_fields)
  509. if loaded_fields:
  510. update_fields = frozenset(loaded_fields)
  511. self.save_base(using=using, force_insert=force_insert,
  512. force_update=force_update, update_fields=update_fields)
  513. save.alters_data = True
  514. def save_base(self, raw=False, force_insert=False,
  515. force_update=False, using=None, update_fields=None):
  516. """
  517. Handles the parts of saving which should be done only once per save,
  518. yet need to be done in raw saves, too. This includes some sanity
  519. checks and signal sending.
  520. The 'raw' argument is telling save_base not to save any parent
  521. models and not to do any changes to the values before save. This
  522. is used by fixture loading.
  523. """
  524. using = using or router.db_for_write(self.__class__, instance=self)
  525. assert not (force_insert and (force_update or update_fields))
  526. assert update_fields is None or len(update_fields) > 0
  527. cls = origin = self.__class__
  528. # Skip proxies, but keep the origin as the proxy model.
  529. if cls._meta.proxy:
  530. cls = cls._meta.concrete_model
  531. meta = cls._meta
  532. if not meta.auto_created:
  533. signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
  534. update_fields=update_fields)
  535. with transaction.commit_on_success_unless_managed(using=using, savepoint=False):
  536. if not raw:
  537. self._save_parents(cls, using, update_fields)
  538. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  539. # Store the database on which the object was saved
  540. self._state.db = using
  541. # Once saved, this is no longer a to-be-added instance.
  542. self._state.adding = False
  543. # Signal that the save is complete
  544. if not meta.auto_created:
  545. signals.post_save.send(sender=origin, instance=self, created=(not updated),
  546. update_fields=update_fields, raw=raw, using=using)
  547. save_base.alters_data = True
  548. def _save_parents(self, cls, using, update_fields):
  549. """
  550. Saves all the parents of cls using values from self.
  551. """
  552. meta = cls._meta
  553. for parent, field in meta.parents.items():
  554. # Make sure the link fields are synced between parent and self.
  555. if (field and getattr(self, parent._meta.pk.attname) is None
  556. and getattr(self, field.attname) is not None):
  557. setattr(self, parent._meta.pk.attname, getattr(self, field.attname))
  558. self._save_parents(cls=parent, using=using, update_fields=update_fields)
  559. self._save_table(cls=parent, using=using, update_fields=update_fields)
  560. # Set the parent's PK value to self.
  561. if field:
  562. setattr(self, field.attname, self._get_pk_val(parent._meta))
  563. # Since we didn't have an instance of the parent handy set
  564. # attname directly, bypassing the descriptor. Invalidate
  565. # the related object cache, in case it's been accidentally
  566. # populated. A fresh instance will be re-built from the
  567. # database if necessary.
  568. cache_name = field.get_cache_name()
  569. if hasattr(self, cache_name):
  570. delattr(self, cache_name)
  571. def _save_table(self, raw=False, cls=None, force_insert=False,
  572. force_update=False, using=None, update_fields=None):
  573. """
  574. Does the heavy-lifting involved in saving. Updates or inserts the data
  575. for a single table.
  576. """
  577. meta = cls._meta
  578. non_pks = [f for f in meta.local_concrete_fields if not f.primary_key]
  579. if update_fields:
  580. non_pks = [f for f in non_pks
  581. if f.name in update_fields or f.attname in update_fields]
  582. pk_val = self._get_pk_val(meta)
  583. pk_set = pk_val is not None
  584. if not pk_set and (force_update or update_fields):
  585. raise ValueError("Cannot force an update in save() with no primary key.")
  586. updated = False
  587. # If possible, try an UPDATE. If that doesn't update anything, do an INSERT.
  588. if pk_set and not force_insert:
  589. base_qs = cls._base_manager.using(using)
  590. values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)))
  591. for f in non_pks]
  592. forced_update = update_fields or force_update
  593. updated = self._do_update(base_qs, using, pk_val, values, update_fields,
  594. forced_update)
  595. if force_update and not updated:
  596. raise DatabaseError("Forced update did not affect any rows.")
  597. if update_fields and not updated:
  598. raise DatabaseError("Save with update_fields did not affect any rows.")
  599. if not updated:
  600. if meta.order_with_respect_to:
  601. # If this is a model with an order_with_respect_to
  602. # autopopulate the _order field
  603. field = meta.order_with_respect_to
  604. order_value = cls._base_manager.using(using).filter(
  605. **{field.name: getattr(self, field.attname)}).count()
  606. self._order = order_value
  607. fields = meta.local_concrete_fields
  608. if not pk_set:
  609. fields = [f for f in fields if not isinstance(f, AutoField)]
  610. update_pk = bool(meta.has_auto_field and not pk_set)
  611. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  612. if update_pk:
  613. setattr(self, meta.pk.attname, result)
  614. return updated
  615. def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update):
  616. """
  617. This method will try to update the model. If the model was updated (in
  618. the sense that an update query was done and a matching row was found
  619. from the DB) the method will return True.
  620. """
  621. filtered = base_qs.filter(pk=pk_val)
  622. if not values:
  623. # We can end up here when saving a model in inheritance chain where
  624. # update_fields doesn't target any field in current model. In that
  625. # case we just say the update succeeded. Another case ending up here
  626. # is a model with just PK - in that case check that the PK still
  627. # exists.
  628. return update_fields is not None or filtered.exists()
  629. if self._meta.select_on_save and not forced_update:
  630. if filtered.exists():
  631. filtered._update(values)
  632. return True
  633. else:
  634. return False
  635. return filtered._update(values) > 0
  636. def _do_insert(self, manager, using, fields, update_pk, raw):
  637. """
  638. Do an INSERT. If update_pk is defined then this method should return
  639. the new pk for the model.
  640. """
  641. return manager._insert([self], fields=fields, return_id=update_pk,
  642. using=using, raw=raw)
  643. def delete(self, using=None):
  644. using = using or router.db_for_write(self.__class__, instance=self)
  645. assert self._get_pk_val() is not None, "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname)
  646. collector = Collector(using=using)
  647. collector.collect([self])
  648. collector.delete()
  649. delete.alters_data = True
  650. def _get_FIELD_display(self, field):
  651. value = getattr(self, field.attname)
  652. return force_text(dict(field.flatchoices).get(value, value), strings_only=True)
  653. def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs):
  654. if not self.pk:
  655. raise ValueError("get_next/get_previous cannot be used on unsaved objects.")
  656. op = 'gt' if is_next else 'lt'
  657. order = '' if is_next else '-'
  658. param = force_text(getattr(self, field.attname))
  659. q = Q(**{'%s__%s' % (field.name, op): param})
  660. q = q | Q(**{field.name: param, 'pk__%s' % op: self.pk})
  661. qs = self.__class__._default_manager.using(self._state.db).filter(**kwargs).filter(q).order_by('%s%s' % (order, field.name), '%spk' % order)
  662. try:
  663. return qs[0]
  664. except IndexError:
  665. raise self.DoesNotExist("%s matching query does not exist." % self.__class__._meta.object_name)
  666. def _get_next_or_previous_in_order(self, is_next):
  667. cachename = "__%s_order_cache" % is_next
  668. if not hasattr(self, cachename):
  669. op = 'gt' if is_next else 'lt'
  670. order = '_order' if is_next else '-_order'
  671. order_field = self._meta.order_with_respect_to
  672. obj = self._default_manager.filter(**{
  673. order_field.name: getattr(self, order_field.attname)
  674. }).filter(**{
  675. '_order__%s' % op: self._default_manager.values('_order').filter(**{
  676. self._meta.pk.name: self.pk
  677. })
  678. }).order_by(order)[:1].get()
  679. setattr(self, cachename, obj)
  680. return getattr(self, cachename)
  681. def prepare_database_save(self, unused):
  682. if self.pk is None:
  683. raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
  684. return self.pk
  685. def clean(self):
  686. """
  687. Hook for doing any extra model-wide validation after clean() has been
  688. called on every field by self.clean_fields. Any ValidationError raised
  689. by this method will not be associated with a particular field; it will
  690. have a special-case association with the field defined by NON_FIELD_ERRORS.
  691. """
  692. pass
  693. def validate_unique(self, exclude=None):
  694. """
  695. Checks unique constraints on the model and raises ``ValidationError``
  696. if any failed.
  697. """
  698. unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
  699. errors = self._perform_unique_checks(unique_checks)
  700. date_errors = self._perform_date_checks(date_checks)
  701. for k, v in date_errors.items():
  702. errors.setdefault(k, []).extend(v)
  703. if errors:
  704. raise ValidationError(errors)
  705. def _get_unique_checks(self, exclude=None):
  706. """
  707. Gather a list of checks to perform. Since validate_unique could be
  708. called from a ModelForm, some fields may have been excluded; we can't
  709. perform a unique check on a model that is missing fields involved
  710. in that check.
  711. Fields that did not validate should also be excluded, but they need
  712. to be passed in via the exclude argument.
  713. """
  714. if exclude is None:
  715. exclude = []
  716. unique_checks = []
  717. unique_togethers = [(self.__class__, self._meta.unique_together)]
  718. for parent_class in self._meta.parents.keys():
  719. if parent_class._meta.unique_together:
  720. unique_togethers.append((parent_class, parent_class._meta.unique_together))
  721. for model_class, unique_together in unique_togethers:
  722. for check in unique_together:
  723. for name in check:
  724. # If this is an excluded field, don't add this check.
  725. if name in exclude:
  726. break
  727. else:
  728. unique_checks.append((model_class, tuple(check)))
  729. # These are checks for the unique_for_<date/year/month>.
  730. date_checks = []
  731. # Gather a list of checks for fields declared as unique and add them to
  732. # the list of checks.
  733. fields_with_class = [(self.__class__, self._meta.local_fields)]
  734. for parent_class in self._meta.parents.keys():
  735. fields_with_class.append((parent_class, parent_class._meta.local_fields))
  736. for model_class, fields in fields_with_class:
  737. for f in fields:
  738. name = f.name
  739. if name in exclude:
  740. continue
  741. if f.unique:
  742. unique_checks.append((model_class, (name,)))
  743. if f.unique_for_date and f.unique_for_date not in exclude:
  744. date_checks.append((model_class, 'date', name, f.unique_for_date))
  745. if f.unique_for_year and f.unique_for_year not in exclude:
  746. date_checks.append((model_class, 'year', name, f.unique_for_year))
  747. if f.unique_for_month and f.unique_for_month not in exclude:
  748. date_checks.append((model_class, 'month', name, f.unique_for_month))
  749. return unique_checks, date_checks
  750. def _perform_unique_checks(self, unique_checks):
  751. errors = {}
  752. for model_class, unique_check in unique_checks:
  753. # Try to look up an existing object with the same values as this
  754. # object's values for all the unique field.
  755. lookup_kwargs = {}
  756. for field_name in unique_check:
  757. f = self._meta.get_field(field_name)
  758. lookup_value = getattr(self, f.attname)
  759. if lookup_value is None:
  760. # no value, skip the lookup
  761. continue
  762. if f.primary_key and not self._state.adding:
  763. # no need to check for unique primary key when editing
  764. continue
  765. lookup_kwargs[str(field_name)] = lookup_value
  766. # some fields were skipped, no reason to do the check
  767. if len(unique_check) != len(lookup_kwargs):
  768. continue
  769. qs = model_class._default_manager.filter(**lookup_kwargs)
  770. # Exclude the current object from the query if we are editing an
  771. # instance (as opposed to creating a new one)
  772. # Note that we need to use the pk as defined by model_class, not
  773. # self.pk. These can be different fields because model inheritance
  774. # allows single model to have effectively multiple primary keys.
  775. # Refs #17615.
  776. model_class_pk = self._get_pk_val(model_class._meta)
  777. if not self._state.adding and model_class_pk is not None:
  778. qs = qs.exclude(pk=model_class_pk)
  779. if qs.exists():
  780. if len(unique_check) == 1:
  781. key = unique_check[0]
  782. else:
  783. key = NON_FIELD_ERRORS
  784. errors.setdefault(key, []).append(self.unique_error_message(model_class, unique_check))
  785. return errors
  786. def _perform_date_checks(self, date_checks):
  787. errors = {}
  788. for model_class, lookup_type, field, unique_for in date_checks:
  789. lookup_kwargs = {}
  790. # there's a ticket to add a date lookup, we can remove this special
  791. # case if that makes it's way in
  792. date = getattr(self, unique_for)
  793. if date is None:
  794. continue
  795. if lookup_type == 'date':
  796. lookup_kwargs['%s__day' % unique_for] = date.day
  797. lookup_kwargs['%s__month' % unique_for] = date.month
  798. lookup_kwargs['%s__year' % unique_for] = date.year
  799. else:
  800. lookup_kwargs['%s__%s' % (unique_for, lookup_type)] = getattr(date, lookup_type)
  801. lookup_kwargs[field] = getattr(self, field)
  802. qs = model_class._default_manager.filter(**lookup_kwargs)
  803. # Exclude the current object from the query if we are editing an
  804. # instance (as opposed to creating a new one)
  805. if not self._state.adding and self.pk is not None:
  806. qs = qs.exclude(pk=self.pk)
  807. if qs.exists():
  808. errors.setdefault(field, []).append(
  809. self.date_error_message(lookup_type, field, unique_for)
  810. )
  811. return errors
  812. def date_error_message(self, lookup_type, field_name, unique_for):
  813. opts = self._meta
  814. field = opts.get_field(field_name)
  815. return ValidationError(
  816. message=field.error_messages['unique_for_date'],
  817. code='unique_for_date',
  818. params={
  819. 'model': self,
  820. 'model_name': six.text_type(capfirst(opts.verbose_name)),
  821. 'lookup_type': lookup_type,
  822. 'field': field_name,
  823. 'field_label': six.text_type(capfirst(field.verbose_name)),
  824. 'date_field': unique_for,
  825. 'date_field_label': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
  826. }
  827. )
  828. def unique_error_message(self, model_class, unique_check):
  829. opts = model_class._meta
  830. params = {
  831. 'model': self,
  832. 'model_class': model_class,
  833. 'model_name': six.text_type(capfirst(opts.verbose_name)),
  834. 'unique_check': unique_check,
  835. }
  836. # A unique field
  837. if len(unique_check) == 1:
  838. field = opts.get_field(unique_check[0])
  839. params['field_label'] = six.text_type(capfirst(field.verbose_name))
  840. return ValidationError(
  841. message=field.error_messages['unique'],
  842. code='unique',
  843. params=params,
  844. )
  845. # unique_together
  846. else:
  847. field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
  848. params['field_labels'] = six.text_type(get_text_list(field_labels, _('and')))
  849. return ValidationError(
  850. message=_("%(model_name)s with this %(field_labels)s already exists."),
  851. code='unique_together',
  852. params=params,
  853. )
  854. def full_clean(self, exclude=None, validate_unique=True):
  855. """
  856. Calls clean_fields, clean, and validate_unique, on the model,
  857. and raises a ``ValidationError`` for any errors that occurred.
  858. """
  859. errors = {}
  860. if exclude is None:
  861. exclude = []
  862. else:
  863. exclude = list(exclude)
  864. try:
  865. self.clean_fields(exclude=exclude)
  866. except ValidationError as e:
  867. errors = e.update_error_dict(errors)
  868. # Form.clean() is run even if other validation fails, so do the
  869. # same with Model.clean() for consistency.
  870. try:
  871. self.clean()
  872. except ValidationError as e:
  873. errors = e.update_error_dict(errors)
  874. # Run unique checks, but only for fields that passed validation.
  875. if validate_unique:
  876. for name in errors.keys():
  877. if name != NON_FIELD_ERRORS and name not in exclude:
  878. exclude.append(name)
  879. try:
  880. self.validate_unique(exclude=exclude)
  881. except ValidationError as e:
  882. errors = e.update_error_dict(errors)
  883. if errors:
  884. raise ValidationError(errors)
  885. def clean_fields(self, exclude=None):
  886. """
  887. Cleans all fields and raises a ValidationError containing a dict
  888. of all validation errors if any occur.
  889. """
  890. if exclude is None:
  891. exclude = []
  892. errors = {}
  893. for f in self._meta.fields:
  894. if f.name in exclude:
  895. continue
  896. # Skip validation for empty fields with blank=True. The developer
  897. # is responsible for making sure they have a valid value.
  898. raw_value = getattr(self, f.attname)
  899. if f.blank and raw_value in f.empty_values:
  900. continue
  901. try:
  902. setattr(self, f.attname, f.clean(raw_value, self))
  903. except ValidationError as e:
  904. errors[f.name] = e.error_list
  905. if errors:
  906. raise ValidationError(errors)
  907. @classmethod
  908. def check(cls, **kwargs):
  909. errors = []
  910. errors.extend(cls._check_swappable())
  911. errors.extend(cls._check_model())
  912. errors.extend(cls._check_managers(**kwargs))
  913. if not cls._meta.swapped:
  914. errors.extend(cls._check_fields(**kwargs))
  915. errors.extend(cls._check_m2m_through_same_relationship())
  916. clash_errors = cls._check_id_field() + cls._check_field_name_clashes()
  917. errors.extend(clash_errors)
  918. # If there are field name clashes, hide consequent column name
  919. # clashes.
  920. if not clash_errors:
  921. errors.extend(cls._check_column_name_clashes())
  922. errors.extend(cls._check_index_together())
  923. errors.extend(cls._check_unique_together())
  924. errors.extend(cls._check_ordering())
  925. return errors
  926. @classmethod
  927. def _check_swappable(cls):
  928. """ Check if the swapped model exists. """
  929. errors = []
  930. if cls._meta.swapped:
  931. try:
  932. apps.get_model(cls._meta.swapped)
  933. except ValueError:
  934. errors.append(
  935. checks.Error(
  936. "'%s' is not of the form 'app_label.app_name'." % cls._meta.swappable,
  937. hint=None,
  938. obj=None,
  939. id='models.E001',
  940. )
  941. )
  942. except LookupError:
  943. app_label, model_name = cls._meta.swapped.split('.')
  944. errors.append(
  945. checks.Error(
  946. ("'%s' references '%s.%s', which has not been installed, or is abstract.") % (
  947. cls._meta.swappable, app_label, model_name
  948. ),
  949. hint=None,
  950. obj=None,
  951. id='models.E002',
  952. )
  953. )
  954. return errors
  955. @classmethod
  956. def _check_model(cls):
  957. errors = []
  958. if cls._meta.proxy:
  959. if cls._meta.local_fields or cls._meta.local_many_to_many:
  960. errors.append(
  961. checks.Error(
  962. "Proxy model '%s' contains model fields." % cls.__name__,
  963. hint=None,
  964. obj=None,
  965. id='models.E017',
  966. )
  967. )
  968. return errors
  969. @classmethod
  970. def _check_managers(cls, **kwargs):
  971. """ Perform all manager checks. """
  972. errors = []
  973. managers = cls._meta.concrete_managers + cls._meta.abstract_managers
  974. for __, __, manager in managers:
  975. errors.extend(manager.check(**kwargs))
  976. return errors
  977. @classmethod
  978. def _check_fields(cls, **kwargs):
  979. """ Perform all field checks. """
  980. errors = []
  981. for field in cls._meta.local_fields:
  982. errors.extend(field.check(**kwargs))
  983. for field in cls._meta.local_many_to_many:
  984. errors.extend(field.check(from_model=cls, **kwargs))
  985. return errors
  986. @classmethod
  987. def _check_m2m_through_same_relationship(cls):
  988. """ Check if no relationship model is used by more than one m2m field.
  989. """
  990. errors = []
  991. seen_intermediary_signatures = []
  992. fields = cls._meta.local_many_to_many
  993. # Skip when the target model wasn't found.
  994. fields = (f for f in fields if isinstance(f.rel.to, ModelBase))
  995. # Skip when the relationship model wasn't found.
  996. fields = (f for f in fields if isinstance(f.rel.through, ModelBase))
  997. for f in fields:
  998. signature = (f.rel.to, cls, f.rel.through)
  999. if signature in seen_intermediary_signatures:
  1000. errors.append(
  1001. checks.Error(
  1002. ("The model has two many-to-many relations through "
  1003. "the intermediate model '%s.%s'.") % (
  1004. f.rel.through._meta.app_label,
  1005. f.rel.through._meta.object_name
  1006. ),
  1007. hint=None,
  1008. obj=cls,
  1009. id='models.E003',
  1010. )
  1011. )
  1012. else:
  1013. seen_intermediary_signatures.append(signature)
  1014. return errors
  1015. @classmethod
  1016. def _check_id_field(cls):
  1017. """ Check if `id` field is a primary key. """
  1018. fields = list(f for f in cls._meta.local_fields
  1019. if f.name == 'id' and f != cls._meta.pk)
  1020. # fields is empty or consists of the invalid "id" field
  1021. if fields and not fields[0].primary_key and cls._meta.pk.name == 'id':
  1022. return [
  1023. checks.Error(
  1024. ("'id' can only be used as a field name if the field also "
  1025. "sets 'primary_key=True'."),
  1026. hint=None,
  1027. obj=cls,
  1028. id='models.E004',
  1029. )
  1030. ]
  1031. else:
  1032. return []
  1033. @classmethod
  1034. def _check_field_name_clashes(cls):
  1035. """ Ref #17673. """
  1036. errors = []
  1037. used_fields = {} # name or attname -> field
  1038. # Check that multi-inheritance doesn't cause field name shadowing.
  1039. for parent in cls._meta.parents:
  1040. for f in parent._meta.local_fields:
  1041. clash = used_fields.get(f.name) or used_fields.get(f.attname) or None
  1042. if clash:
  1043. errors.append(
  1044. checks.Error(
  1045. ("The field '%s' from parent model "
  1046. "'%s' clashes with the field '%s' "
  1047. "from parent model '%s'.") % (
  1048. clash.name, clash.model._meta,
  1049. f.name, f.model._meta
  1050. ),
  1051. hint=None,
  1052. obj=cls,
  1053. id='models.E005',
  1054. )
  1055. )
  1056. used_fields[f.name] = f
  1057. used_fields[f.attname] = f
  1058. # Check that fields defined in the model don't clash with fields from
  1059. # parents.
  1060. for f in cls._meta.local_fields:
  1061. clash = used_fields.get(f.name) or used_fields.get(f.attname) or None
  1062. # Note that we may detect clash between user-defined non-unique
  1063. # field "id" and automatically added unique field "id", both
  1064. # defined at the same model. This special case is considered in
  1065. # _check_id_field and here we ignore it.
  1066. id_conflict = (f.name == "id" and
  1067. clash and clash.name == "id" and clash.model == cls)
  1068. if clash and not id_conflict:
  1069. errors.append(
  1070. checks.Error(
  1071. ("The field '%s' clashes with the field '%s' "
  1072. "from model '%s'.") % (
  1073. f.name, clash.name, clash.model._meta
  1074. ),
  1075. hint=None,
  1076. obj=f,
  1077. id='models.E006',
  1078. )
  1079. )
  1080. used_fields[f.name] = f
  1081. used_fields[f.attname] = f
  1082. return errors
  1083. @classmethod
  1084. def _check_column_name_clashes(cls):
  1085. # Store a list of column names which have already been used by other fields.
  1086. used_column_names = []
  1087. errors = []
  1088. for f in cls._meta.local_fields:
  1089. _, column_name = f.get_attname_column()
  1090. # Ensure the column name is not already in use.
  1091. if column_name and column_name in used_column_names:
  1092. errors.append(
  1093. checks.Error(
  1094. "Field '%s' has column name '%s' that is used by another field." % (f.name, column_name),
  1095. hint="Specify a 'db_column' for the field.",
  1096. obj=cls,
  1097. id='models.E007'
  1098. )
  1099. )
  1100. else:
  1101. used_column_names.append(column_name)
  1102. return errors
  1103. @classmethod
  1104. def _check_index_together(cls):
  1105. """ Check the value of "index_together" option. """
  1106. if not isinstance(cls._meta.index_together, (tuple, list)):
  1107. return [
  1108. checks.Error(
  1109. "'index_together' must be a list or tuple.",
  1110. hint=None,
  1111. obj=cls,
  1112. id='models.E008',
  1113. )
  1114. ]
  1115. elif any(not isinstance(fields, (tuple, list))
  1116. for fields in cls._meta.index_together):
  1117. return [
  1118. checks.Error(
  1119. "All 'index_together' elements must be lists or tuples.",
  1120. hint=None,
  1121. obj=cls,
  1122. id='models.E009',
  1123. )
  1124. ]
  1125. else:
  1126. errors = []
  1127. for fields in cls._meta.index_together:
  1128. errors.extend(cls._check_local_fields(fields, "index_together"))
  1129. return errors
  1130. @classmethod
  1131. def _check_unique_together(cls):
  1132. """ Check the value of "unique_together" option. """
  1133. if not isinstance(cls._meta.unique_together, (tuple, list)):
  1134. return [
  1135. checks.Error(
  1136. "'unique_together' must be a list or tuple.",
  1137. hint=None,
  1138. obj=cls,
  1139. id='models.E010',
  1140. )
  1141. ]
  1142. elif any(not isinstance(fields, (tuple, list))
  1143. for fields in cls._meta.unique_together):
  1144. return [
  1145. checks.Error(
  1146. "All 'unique_together' elements must be lists or tuples.",
  1147. hint=None,
  1148. obj=cls,
  1149. id='models.E011',
  1150. )
  1151. ]
  1152. else:
  1153. errors = []
  1154. for fields in cls._meta.unique_together:
  1155. errors.extend(cls._check_local_fields(fields, "unique_together"))
  1156. return errors
  1157. @classmethod
  1158. def _check_local_fields(cls, fields, option):
  1159. from django.db import models
  1160. errors = []
  1161. for field_name in fields:
  1162. try:
  1163. field = cls._meta.get_field(field_name,
  1164. many_to_many=True)
  1165. except models.FieldDoesNotExist:
  1166. errors.append(
  1167. checks.Error(
  1168. "'%s' refers to the non-existent field '%s'." % (option, field_name),
  1169. hint=None,
  1170. obj=cls,
  1171. id='models.E012',
  1172. )
  1173. )
  1174. else:
  1175. if isinstance(field.rel, models.ManyToManyRel):
  1176. errors.append(
  1177. checks.Error(
  1178. ("'%s' refers to a ManyToManyField '%s', but "
  1179. "ManyToManyFields are not permitted in '%s'.") % (
  1180. option, field_name, option
  1181. ),
  1182. hint=None,
  1183. obj=cls,
  1184. id='models.E013',
  1185. )
  1186. )
  1187. return errors
  1188. @classmethod
  1189. def _check_ordering(cls):
  1190. """ Check "ordering" option -- is it a list of strings and do all fields
  1191. exist? """
  1192. from django.db.models import FieldDoesNotExist
  1193. if not cls._meta.ordering:
  1194. return []
  1195. if not isinstance(cls._meta.ordering, (list, tuple)):
  1196. return [
  1197. checks.Error(
  1198. ("'ordering' must be a tuple or list "
  1199. "(even if you want to order by only one field)."),
  1200. hint=None,
  1201. obj=cls,
  1202. id='models.E014',
  1203. )
  1204. ]
  1205. errors = []
  1206. fields = cls._meta.ordering
  1207. # Skip '?' fields.
  1208. fields = (f for f in fields if f != '?')
  1209. # Convert "-field" to "field".
  1210. fields = ((f[1:] if f.startswith('-') else f) for f in fields)
  1211. fields = (f for f in fields if
  1212. f != '_order' or not cls._meta.order_with_respect_to)
  1213. # Skip ordering in the format field1__field2 (FIXME: checking
  1214. # this format would be nice, but it's a little fiddly).
  1215. fields = (f for f in fields if '__' not in f)
  1216. # Skip ordering on pk. This is always a valid order_by field
  1217. # but is an alias and therefore won't be found by opts.get_field.
  1218. fields = (f for f in fields if f != 'pk')
  1219. for field_name in fields:
  1220. try:
  1221. cls._meta.get_field(field_name, many_to_many=False)
  1222. except FieldDoesNotExist:
  1223. if field_name.endswith('_id'):
  1224. try:
  1225. field = cls._meta.get_field(field_name[:-3], many_to_many=False)
  1226. except FieldDoesNotExist:
  1227. pass
  1228. else:
  1229. if field.attname == field_name:
  1230. continue
  1231. errors.append(
  1232. checks.Error(
  1233. "'ordering' refers to the non-existent field '%s'." % field_name,
  1234. hint=None,
  1235. obj=cls,
  1236. id='models.E015',
  1237. )
  1238. )
  1239. return errors
  1240. ############################################
  1241. # HELPER FUNCTIONS (CURRIED MODEL METHODS) #
  1242. ############################################
  1243. # ORDERING METHODS #########################
  1244. def method_set_order(ordered_obj, self, id_list, using=None):
  1245. if using is None:
  1246. using = DEFAULT_DB_ALIAS
  1247. rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name)
  1248. order_name = ordered_obj._meta.order_with_respect_to.name
  1249. # FIXME: It would be nice if there was an "update many" version of update
  1250. # for situations like this.
  1251. with transaction.commit_on_success_unless_managed(using=using):
  1252. for i, j in enumerate(id_list):
  1253. ordered_obj.objects.filter(**{'pk': j, order_name: rel_val}).update(_order=i)
  1254. def method_get_order(ordered_obj, self):
  1255. rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name)
  1256. order_name = ordered_obj._meta.order_with_respect_to.name
  1257. pk_name = ordered_obj._meta.pk.name
  1258. return [r[pk_name] for r in
  1259. ordered_obj.objects.filter(**{order_name: rel_val}).values(pk_name)]
  1260. ##############################################
  1261. # HELPER FUNCTIONS (CURRIED MODEL FUNCTIONS) #
  1262. ##############################################
  1263. def get_absolute_url(opts, func, self, *args, **kwargs):
  1264. return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.model_name), func)(self, *args, **kwargs)
  1265. ########
  1266. # MISC #
  1267. ########
  1268. def simple_class_factory(model, attrs):
  1269. """
  1270. Needed for dynamic classes.
  1271. """
  1272. return model
  1273. def model_unpickle(model_id, attrs, factory):
  1274. """
  1275. Used to unpickle Model subclasses with deferred fields.
  1276. """
  1277. if isinstance(model_id, tuple):
  1278. model = apps.get_model(*model_id)
  1279. else:
  1280. # Backwards compat - the model was cached directly in earlier versions.
  1281. model = model_id
  1282. cls = factory(model, attrs)
  1283. return cls.__new__(cls)
  1284. model_unpickle.__safe_for_unpickle__ = True
  1285. def unpickle_inner_exception(klass, exception_name):
  1286. # Get the exception class from the class it is attached to:
  1287. exception = getattr(klass, exception_name)
  1288. return exception.__new__(exception)