PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

Plain Text | 1236 lines | 935 code | 301 blank | 0 comment | 0 complexity | 18377b9c58493332c8747f9cae5edc36 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. ======
  2. Models
  3. ======
  4. .. module:: django.db.models
  5. A model is the single, definitive source of data about your data. It contains
  6. the essential fields and behaviors of the data you're storing. Generally, each
  7. model maps to a single database table.
  8. The basics:
  9. * Each model is a Python class that subclasses
  10. :class:`django.db.models.Model`.
  11. * Each attribute of the model represents a database field.
  12. * With all of this, Django gives you an automatically-generated
  13. database-access API; see :doc:`/topics/db/queries`.
  14. .. seealso::
  15. A companion to this document is the `official repository of model
  16. examples`_. (In the Django source distribution, these examples are in the
  17. ``tests/modeltests`` directory.)
  18. .. _official repository of model examples:
  19. Quick example
  20. =============
  21. This example model defines a ``Person``, which has a ``first_name`` and
  22. ``last_name``::
  23. from django.db import models
  24. class Person(models.Model):
  25. first_name = models.CharField(max_length=30)
  26. last_name = models.CharField(max_length=30)
  27. ``first_name`` and ``last_name`` are fields_ of the model. Each field is
  28. specified as a class attribute, and each attribute maps to a database column.
  29. The above ``Person`` model would create a database table like this:
  30. .. code-block:: sql
  31. CREATE TABLE myapp_person (
  32. "id" serial NOT NULL PRIMARY KEY,
  33. "first_name" varchar(30) NOT NULL,
  34. "last_name" varchar(30) NOT NULL
  35. );
  36. Some technical notes:
  37. * The name of the table, ``myapp_person``, is automatically derived from
  38. some model metadata but can be overridden. See :ref:`table-names` for more
  39. details..
  40. * An ``id`` field is added automatically, but this behavior can be
  41. overridden. See :ref:`automatic-primary-key-fields`.
  42. * The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL
  43. syntax, but it's worth noting Django uses SQL tailored to the database
  44. backend specified in your :doc:`settings file </topics/settings>`.
  45. Using models
  46. ============
  47. Once you have defined your models, you need to tell Django you're going to *use*
  48. those models. Do this by editing your settings file and changing the
  49. :setting:`INSTALLED_APPS` setting to add the name of the module that contains
  50. your ````.
  51. For example, if the models for your application live in the module
  52. ``mysite.myapp.models`` (the package structure that is created for an
  53. application by the :djadmin:` startapp <startapp>` script),
  54. :setting:`INSTALLED_APPS` should read, in part::
  56. #...
  57. 'mysite.myapp',
  58. #...
  59. )
  60. When you add new apps to :setting:`INSTALLED_APPS`, be sure to run
  61. :djadmin:` syncdb <syncdb>`.
  62. Fields
  63. ======
  64. The most important part of a model -- and the only required part of a model --
  65. is the list of database fields it defines. Fields are specified by class
  66. attributes.
  67. Example::
  68. class Musician(models.Model):
  69. first_name = models.CharField(max_length=50)
  70. last_name = models.CharField(max_length=50)
  71. instrument = models.CharField(max_length=100)
  72. class Album(models.Model):
  73. artist = models.ForeignKey(Musician)
  74. name = models.CharField(max_length=100)
  75. release_date = models.DateField()
  76. num_stars = models.IntegerField()
  77. Field types
  78. -----------
  79. Each field in your model should be an instance of the appropriate
  80. :class:`~django.db.models.Field` class. Django uses the field class types to
  81. determine a few things:
  82. * The database column type (e.g. ``INTEGER``, ``VARCHAR``).
  83. * The :doc:`widget </ref/forms/widgets>` to use in Django's admin interface,
  84. if you care to use it (e.g. ``<input type="text">``, ``<select>``).
  85. * The minimal validation requirements, used in Django's admin and in
  86. automatically-generated forms.
  87. Django ships with dozens of built-in field types; you can find the complete list
  88. in the :ref:`model field reference <model-field-types>`. You can easily write
  89. your own fields if Django's built-in ones don't do the trick; see
  90. :doc:`/howto/custom-model-fields`.
  91. Field options
  92. -------------
  93. Each field takes a certain set of field-specific arguments (documented in the
  94. :ref:`model field reference <model-field-types>`). For example,
  95. :class:`~django.db.models.CharField` (and its subclasses) require a
  96. :attr:`~django.db.models.CharField.max_length` argument which specifies the size
  97. of the ``VARCHAR`` database field used to store the data.
  98. There's also a set of common arguments available to all field types. All are
  99. optional. They're fully explained in the :ref:`reference
  100. <common-model-field-options>`, but here's a quick summary of the most often-used
  101. ones:
  102. :attr:`~Field.null`
  103. If ``True``, Django will store empty values as ``NULL`` in the database.
  104. Default is ``False``.
  105. :attr:`~Field.blank`
  106. If ``True``, the field is allowed to be blank. Default is ``False``.
  107. Note that this is different than :attr:`~Field.null`.
  108. :attr:`~Field.null` is purely database-related, whereas
  109. :attr:`~Field.blank` is validation-related. If a field has
  110. :attr:`blank=True <Field.blank>`, validation on Django's admin site will
  111. allow entry of an empty value. If a field has :attr:`blank=False
  112. <Field.blank>`, the field will be required.
  113. :attr:`~Field.choices`
  114. An iterable (e.g., a list or tuple) of 2-tuples to use as choices for
  115. this field. If this is given, Django's admin will use a select box
  116. instead of the standard text field and will limit choices to the choices
  117. given.
  118. A choices list looks like this::
  120. (u'FR', u'Freshman'),
  121. (u'SO', u'Sophomore'),
  122. (u'JR', u'Junior'),
  123. (u'SR', u'Senior'),
  124. (u'GR', u'Graduate'),
  125. )
  126. The first element in each tuple is the value that will be stored in the
  127. database, the second element will be displayed by the admin interface,
  128. or in a ModelChoiceField. Given an instance of a model object, the
  129. display value for a choices field can be accessed using the
  130. ``get_FOO_display`` method. For example::
  131. from django.db import models
  132. class Person(models.Model):
  134. (u'M', u'Male'),
  135. (u'F', u'Female'),
  136. )
  137. name = models.CharField(max_length=60)
  138. gender = models.CharField(max_length=2, choices=GENDER_CHOICES)
  139. ::
  140. >>> p = Person(name="Fred Flintstone", gender="M")
  141. >>>
  142. >>> p.gender
  143. u'M'
  144. >>> p.get_gender_display()
  145. u'Male'
  146. :attr:`~Field.default`
  147. The default value for the field. This can be a value or a callable
  148. object. If callable it will be called every time a new object is
  149. created.
  150. :attr:`~Field.help_text`
  151. Extra "help" text to be displayed under the field on the object's admin
  152. form. It's useful for documentation even if your object doesn't have an
  153. admin form.
  154. :attr:`~Field.primary_key`
  155. If ``True``, this field is the primary key for the model.
  156. If you don't specify :attr:`primary_key=True <Field.primary_key>` for
  157. any fields in your model, Django will automatically add an
  158. :class:`IntegerField` to hold the primary key, so you don't need to set
  159. :attr:`primary_key=True <Field.primary_key>` on any of your fields
  160. unless you want to override the default primary-key behavior. For more,
  161. see :ref:`automatic-primary-key-fields`.
  162. :attr:`~Field.unique`
  163. If ``True``, this field must be unique throughout the table.
  164. Again, these are just short descriptions of the most common field options. Full
  165. details can be found in the :ref:`common model field option reference
  166. <common-model-field-options>`.
  167. .. _automatic-primary-key-fields:
  168. Automatic primary key fields
  169. ----------------------------
  170. By default, Django gives each model the following field::
  171. id = models.AutoField(primary_key=True)
  172. This is an auto-incrementing primary key.
  173. If you'd like to specify a custom primary key, just specify
  174. :attr:`primary_key=True <Field.primary_key>` on one of your fields. If Django
  175. sees you've explicitly set :attr:`Field.primary_key`, it won't add the automatic
  176. ``id`` column.
  177. Each model requires exactly one field to have :attr:`primary_key=True
  178. <Field.primary_key>`.
  179. .. _verbose-field-names:
  180. Verbose field names
  181. -------------------
  182. Each field type, except for :class:`~django.db.models.ForeignKey`,
  183. :class:`~django.db.models.ManyToManyField` and
  184. :class:`~django.db.models.OneToOneField`, takes an optional first positional
  185. argument -- a verbose name. If the verbose name isn't given, Django will
  186. automatically create it using the field's attribute name, converting underscores
  187. to spaces.
  188. In this example, the verbose name is ``"person's first name"``::
  189. first_name = models.CharField("person's first name", max_length=30)
  190. In this example, the verbose name is ``"first name"``::
  191. first_name = models.CharField(max_length=30)
  192. :class:`~django.db.models.ForeignKey`,
  193. :class:`~django.db.models.ManyToManyField` and
  194. :class:`~django.db.models.OneToOneField` require the first argument to be a
  195. model class, so use the :attr:`~Field.verbose_name` keyword argument::
  196. poll = models.ForeignKey(Poll, verbose_name="the related poll")
  197. sites = models.ManyToManyField(Site, verbose_name="list of sites")
  198. place = models.OneToOneField(Place, verbose_name="related place")
  199. The convention is not to capitalize the first letter of the
  200. :attr:`~Field.verbose_name`. Django will automatically capitalize the first
  201. letter where it needs to.
  202. Relationships
  203. -------------
  204. Clearly, the power of relational databases lies in relating tables to each
  205. other. Django offers ways to define the three most common types of database
  206. relationships: many-to-one, many-to-many and one-to-one.
  207. Many-to-one relationships
  208. ~~~~~~~~~~~~~~~~~~~~~~~~~
  209. To define a many-to-one relationship, use :class:`django.db.models.ForeignKey`.
  210. You use it just like any other :class:`~django.db.models.Field` type: by
  211. including it as a class attribute of your model.
  212. :class:`~django.db.models.ForeignKey` requires a positional argument: the class
  213. to which the model is related.
  214. For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
  215. ``Manufacturer`` makes multiple cars but each ``Car`` only has one
  216. ``Manufacturer`` -- use the following definitions::
  217. class Manufacturer(models.Model):
  218. # ...
  219. class Car(models.Model):
  220. manufacturer = models.ForeignKey(Manufacturer)
  221. # ...
  222. You can also create :ref:`recursive relationships <recursive-relationships>` (an
  223. object with a many-to-one relationship to itself) and :ref:`relationships to
  224. models not yet defined <lazy-relationships>`; see :ref:`the model field
  225. reference <ref-foreignkey>` for details.
  226. It's suggested, but not required, that the name of a
  227. :class:`~django.db.models.ForeignKey` field (``manufacturer`` in the example
  228. above) be the name of the model, lowercase. You can, of course, call the field
  229. whatever you want. For example::
  230. class Car(models.Model):
  231. company_that_makes_it = models.ForeignKey(Manufacturer)
  232. # ...
  233. .. seealso::
  234. :class:`~django.db.models.ForeignKey` fields accept a number of extra
  235. arguments which are explained in :ref:`the model field reference
  236. <foreign-key-arguments>`. These options help define how the relationship
  237. should work; all are optional.
  238. For details on accessing backwards-related objects, see the
  239. `Following relationships backward example`_.
  240. For sample code, see the `Many-to-one relationship model tests`_.
  241. .. _Following relationships backward example:
  242. .. _Many-to-one relationship model tests:
  243. Many-to-many relationships
  244. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  245. To define a many-to-many relationship, use
  246. :class:`~django.db.models.ManyToManyField`. You use it just like any other
  247. :class:`~django.db.models.Field` type: by including it as a class attribute of
  248. your model.
  249. :class:`~django.db.models.ManyToManyField` requires a positional argument: the
  250. class to which the model is related.
  251. For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
  252. ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings
  253. -- here's how you'd represent that::
  254. class Topping(models.Model):
  255. # ...
  256. class Pizza(models.Model):
  257. # ...
  258. toppings = models.ManyToManyField(Topping)
  259. As with :class:`~django.db.models.ForeignKey`, you can also create
  260. :ref:`recursive relationships <recursive-relationships>` (an object with a
  261. many-to-many relationship to itself) and :ref:`relationships to models not yet
  262. defined <lazy-relationships>`; see :ref:`the model field reference
  263. <ref-manytomany>` for details.
  264. It's suggested, but not required, that the name of a
  265. :class:`~django.db.models.ManyToManyField` (``toppings`` in the example above)
  266. be a plural describing the set of related model objects.
  267. It doesn't matter which model gets the
  268. :class:`~django.db.models.ManyToManyField`, but you only need it in one of the
  269. models -- not in both.
  270. Generally, :class:`~django.db.models.ManyToManyField` instances should go in the
  271. object that's going to be edited in the admin interface, if you're using
  272. Django's admin. In the above example, ``toppings`` is in ``Pizza`` (rather than
  273. ``Topping`` having a ``pizzas`` :class:`~django.db.models.ManyToManyField` )
  274. because it's more natural to think about a pizza having toppings than a
  275. topping being on multiple pizzas. The way it's set up above, the ``Pizza`` admin
  276. form would let users select the toppings.
  277. .. seealso::
  278. See the `Many-to-many relationship model example`_ for a full example.
  279. .. _Many-to-many relationship model example:
  280. :class:`~django.db.models.ManyToManyField` fields also accept a number of extra
  281. arguments which are explained in :ref:`the model field reference
  282. <manytomany-arguments>`. These options help define how the relationship should
  283. work; all are optional.
  284. .. _intermediary-manytomany:
  285. Extra fields on many-to-many relationships
  286. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  287. When you're only dealing with simple many-to-many relationships such as
  288. mixing and matching pizzas and toppings, a standard :class:`~django.db.models.ManyToManyField` is all you need. However, sometimes
  289. you may need to associate data with the relationship between two models.
  290. For example, consider the case of an application tracking the musical groups
  291. which musicians belong to. There is a many-to-many relationship between a person
  292. and the groups of which they are a member, so you could use a
  293. :class:`~django.db.models.ManyToManyField` to represent this relationship.
  294. However, there is a lot of detail about the membership that you might want to
  295. collect, such as the date at which the person joined the group.
  296. For these situations, Django allows you to specify the model that will be used
  297. to govern the many-to-many relationship. You can then put extra fields on the
  298. intermediate model. The intermediate model is associated with the
  299. :class:`~django.db.models.ManyToManyField` using the
  300. :attr:`through <ManyToManyField.through>` argument to point to the model
  301. that will act as an intermediary. For our musician example, the code would look
  302. something like this::
  303. class Person(models.Model):
  304. name = models.CharField(max_length=128)
  305. def __unicode__(self):
  306. return
  307. class Group(models.Model):
  308. name = models.CharField(max_length=128)
  309. members = models.ManyToManyField(Person, through='Membership')
  310. def __unicode__(self):
  311. return
  312. class Membership(models.Model):
  313. person = models.ForeignKey(Person)
  314. group = models.ForeignKey(Group)
  315. date_joined = models.DateField()
  316. invite_reason = models.CharField(max_length=64)
  317. When you set up the intermediary model, you explicitly specify foreign
  318. keys to the models that are involved in the ManyToMany relation. This
  319. explicit declaration defines how the two models are related.
  320. There are a few restrictions on the intermediate model:
  321. * Your intermediate model must contain one - and *only* one - foreign key
  322. to the target model (this would be ``Person`` in our example). If you
  323. have more than one foreign key, a validation error will be raised.
  324. * Your intermediate model must contain one - and *only* one - foreign key
  325. to the source model (this would be ``Group`` in our example). If you
  326. have more than one foreign key, a validation error will be raised.
  327. * The only exception to this is a model which has a many-to-many
  328. relationship to itself, through an intermediary model. In this
  329. case, two foreign keys to the same model are permitted, but they
  330. will be treated as the two (different) sides of the many-to-many
  331. relation.
  332. * When defining a many-to-many relationship from a model to
  333. itself, using an intermediary model, you *must* use
  334. :attr:`symmetrical=False <ManyToManyField.symmetrical>` (see
  335. :ref:`the model field reference <manytomany-arguments>`).
  336. Now that you have set up your :class:`~django.db.models.ManyToManyField` to use
  337. your intermediary model (``Membership``, in this case), you're ready to start
  338. creating some many-to-many relationships. You do this by creating instances of
  339. the intermediate model::
  340. >>> ringo = Person.objects.create(name="Ringo Starr")
  341. >>> paul = Person.objects.create(name="Paul McCartney")
  342. >>> beatles = Group.objects.create(name="The Beatles")
  343. >>> m1 = Membership(person=ringo, group=beatles,
  344. ... date_joined=date(1962, 8, 16),
  345. ... invite_reason= "Needed a new drummer.")
  346. >>>
  347. >>> beatles.members.all()
  348. [<Person: Ringo Starr>]
  349. >>> ringo.group_set.all()
  350. [<Group: The Beatles>]
  351. >>> m2 = Membership.objects.create(person=paul, group=beatles,
  352. ... date_joined=date(1960, 8, 1),
  353. ... invite_reason= "Wanted to form a band.")
  354. >>> beatles.members.all()
  355. [<Person: Ringo Starr>, <Person: Paul McCartney>]
  356. Unlike normal many-to-many fields, you *can't* use ``add``, ``create``,
  357. or assignment (i.e., ``beatles.members = [...]``) to create relationships::
  359. >>> beatles.members.add(john)
  361. >>> beatles.members.create(name="George Harrison")
  363. >>> beatles.members = [john, paul, ringo, george]
  364. Why? You can't just create a relationship between a ``Person`` and a ``Group``
  365. - you need to specify all the detail for the relationship required by the
  366. ``Membership`` model. The simple ``add``, ``create`` and assignment calls
  367. don't provide a way to specify this extra detail. As a result, they are
  368. disabled for many-to-many relationships that use an intermediate model.
  369. The only way to create this type of relationship is to create instances of the
  370. intermediate model.
  371. The :meth:`~django.db.models.fields.related.RelatedManager.remove` method is
  372. disabled for similar reasons. However, the
  373. :meth:`~django.db.models.fields.related.RelatedManager.clear` method can be
  374. used to remove all many-to-many relationships for an instance::
  375. # Beatles have broken up
  376. >>> beatles.members.clear()
  377. Once you have established the many-to-many relationships by creating instances
  378. of your intermediate model, you can issue queries. Just as with normal
  379. many-to-many relationships, you can query using the attributes of the
  380. many-to-many-related model::
  381. # Find all the groups with a member whose name starts with 'Paul'
  382. >>> Group.objects.filter(members__name__startswith='Paul')
  383. [<Group: The Beatles>]
  384. As you are using an intermediate model, you can also query on its attributes::
  385. # Find all the members of the Beatles that joined after 1 Jan 1961
  386. >>> Person.objects.filter(
  387. ... group__name='The Beatles',
  388. ... membership__date_joined__gt=date(1961,1,1))
  389. [<Person: Ringo Starr]
  390. One-to-one relationships
  391. ~~~~~~~~~~~~~~~~~~~~~~~~
  392. To define a one-to-one relationship, use
  393. :class:`~django.db.models.OneToOneField`. You use it just like any other
  394. ``Field`` type: by including it as a class attribute of your model.
  395. This is most useful on the primary key of an object when that object "extends"
  396. another object in some way.
  397. :class:`~django.db.models.OneToOneField` requires a positional argument: the
  398. class to which the model is related.
  399. For example, if you were building a database of "places", you would
  400. build pretty standard stuff such as address, phone number, etc. in the
  401. database. Then, if you wanted to build a database of restaurants on
  402. top of the places, instead of repeating yourself and replicating those
  403. fields in the ``Restaurant`` model, you could make ``Restaurant`` have
  404. a :class:`~django.db.models.OneToOneField` to ``Place`` (because a
  405. restaurant "is a" place; in fact, to handle this you'd typically use
  406. :ref:`inheritance <model-inheritance>`, which involves an implicit
  407. one-to-one relation).
  408. As with :class:`~django.db.models.ForeignKey`, a
  409. :ref:`recursive relationship <recursive-relationships>`
  410. can be defined and
  411. :ref:`references to as-yet undefined models <lazy-relationships>`
  412. can be made; see :ref:`the model field reference <ref-onetoone>` for details.
  413. .. seealso::
  414. See the `One-to-one relationship model example`_ for a full example.
  415. .. _One-to-one relationship model example:
  416. :class:`~django.db.models.OneToOneField` fields also accept one optional argument
  417. described in the :ref:`model field reference <ref-onetoone>`.
  418. :class:`~django.db.models.OneToOneField` classes used to automatically become
  419. the primary key on a model. This is no longer true (although you can manually
  420. pass in the :attr:`~django.db.models.Field.primary_key` argument if you like).
  421. Thus, it's now possible to have multiple fields of type
  422. :class:`~django.db.models.OneToOneField` on a single model.
  423. Models across files
  424. -------------------
  425. It's perfectly OK to relate a model to one from another app. To do this,
  426. import the related model at the top of the model that holds your model. Then,
  427. just refer to the other model class wherever needed. For example::
  428. from geography.models import ZipCode
  429. class Restaurant(models.Model):
  430. # ...
  431. zip_code = models.ForeignKey(ZipCode)
  432. Field name restrictions
  433. -----------------------
  434. Django places only two restrictions on model field names:
  435. 1. A field name cannot be a Python reserved word, because that would result
  436. in a Python syntax error. For example::
  437. class Example(models.Model):
  438. pass = models.IntegerField() # 'pass' is a reserved word!
  439. 2. A field name cannot contain more than one underscore in a row, due to
  440. the way Django's query lookup syntax works. For example::
  441. class Example(models.Model):
  442. foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
  443. These limitations can be worked around, though, because your field name doesn't
  444. necessarily have to match your database column name. See the
  445. :attr:`~Field.db_column` option.
  446. SQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as
  447. model field names, because Django escapes all database table names and column
  448. names in every underlying SQL query. It uses the quoting syntax of your
  449. particular database engine.
  450. Custom field types
  451. ------------------
  452. If one of the existing model fields cannot be used to fit your purposes, or if
  453. you wish to take advantage of some less common database column types, you can
  454. create your own field class. Full coverage of creating your own fields is
  455. provided in :doc:`/howto/custom-model-fields`.
  456. .. _meta-options:
  457. Meta options
  458. ============
  459. Give your model metadata by using an inner ``class Meta``, like so::
  460. class Ox(models.Model):
  461. horn_length = models.IntegerField()
  462. class Meta:
  463. ordering = ["horn_length"]
  464. verbose_name_plural = "oxen"
  465. Model metadata is "anything that's not a field", such as ordering options
  466. (:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), or
  467. human-readable singular and plural names (:attr:`~Options.verbose_name` and
  468. :attr:`~Options.verbose_name_plural`). None are required, and adding ``class
  469. Meta`` to a model is completely optional.
  470. A complete list of all possible ``Meta`` options can be found in the :doc:`model
  471. option reference </ref/models/options>`.
  472. .. _model-methods:
  473. Model methods
  474. =============
  475. Define custom methods on a model to add custom "row-level" functionality to your
  476. objects. Whereas :class:`~django.db.models.Manager` methods are intended to do
  477. "table-wide" things, model methods should act on a particular model instance.
  478. This is a valuable technique for keeping business logic in one place -- the
  479. model.
  480. For example, this model has a few custom methods::
  481. from import USStateField
  482. class Person(models.Model):
  483. first_name = models.CharField(max_length=50)
  484. last_name = models.CharField(max_length=50)
  485. birth_date = models.DateField()
  486. address = models.CharField(max_length=100)
  487. city = models.CharField(max_length=50)
  488. state = USStateField() # Yes, this is America-centric...
  489. def baby_boomer_status(self):
  490. "Returns the person's baby-boomer status."
  491. import datetime
  492. if, 8, 1) <= self.birth_date <=, 12, 31):
  493. return "Baby boomer"
  494. if self.birth_date <, 8, 1):
  495. return "Pre-boomer"
  496. return "Post-boomer"
  497. def is_midwestern(self):
  498. "Returns True if this person is from the Midwest."
  499. return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')
  500. def _get_full_name(self):
  501. "Returns the person's full name."
  502. return '%s %s' % (self.first_name, self.last_name)
  503. full_name = property(_get_full_name)
  504. The last method in this example is a :term:`property`. `Read more about
  505. properties`_.
  506. .. _Read more about properties:
  507. The :doc:`model instance reference </ref/models/instances>` has a complete list
  508. of :ref:`methods automatically given to each model <model-instance-methods>`.
  509. You can override most of these -- see `overriding predefined model methods`_,
  510. below -- but there are a couple that you'll almost always want to define:
  511. :meth:`~Model.__unicode__`
  512. A Python "magic method" that returns a unicode "representation" of any
  513. object. This is what Python and Django will use whenever a model
  514. instance needs to be coerced and displayed as a plain string. Most
  515. notably, this happens when you display an object in an interactive
  516. console or in the admin.
  517. You'll always want to define this method; the default isn't very helpful
  518. at all.
  519. :meth:`~Model.get_absolute_url`
  520. This tells Django how to calculate the URL for an object. Django uses
  521. this in its admin interface, and any time it needs to figure out a URL
  522. for an object.
  523. Any object that has a URL that uniquely identifies it should define this
  524. method.
  525. .. _overriding-model-methods:
  526. Overriding predefined model methods
  527. -----------------------------------
  528. There's another set of :ref:`model methods <model-instance-methods>` that
  529. encapsulate a bunch of database behavior that you'll want to customize. In
  530. particular you'll often want to change the way :meth:`` and
  531. :meth:`~Model.delete` work.
  532. You're free to override these methods (and any other model method) to alter
  533. behavior.
  534. A classic use-case for overriding the built-in methods is if you want something
  535. to happen whenever you save an object. For example (see
  536. :meth:`` for documentation of the parameters it accepts)::
  537. class Blog(models.Model):
  538. name = models.CharField(max_length=100)
  539. tagline = models.TextField()
  540. def save(self, *args, **kwargs):
  541. do_something()
  542. super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
  543. do_something_else()
  544. You can also prevent saving::
  545. class Blog(models.Model):
  546. name = models.CharField(max_length=100)
  547. tagline = models.TextField()
  548. def save(self, *args, **kwargs):
  549. if == "Yoko Ono's blog":
  550. return # Yoko shall never have her own blog!
  551. else:
  552. super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
  553. It's important to remember to call the superclass method -- that's
  554. that ``super(Blog, self).save(*args, **kwargs)`` business -- to ensure
  555. that the object still gets saved into the database. If you forget to
  556. call the superclass method, the default behavior won't happen and the
  557. database won't get touched.
  558. It's also important that you pass through the arguments that can be
  559. passed to the model method -- that's what the ``*args, **kwargs`` bit
  560. does. Django will, from time to time, extend the capabilities of
  561. built-in model methods, adding new arguments. If you use ``*args,
  562. **kwargs`` in your method definitions, you are guaranteed that your
  563. code will automatically support those arguments when they are added.
  564. .. admonition:: Overriding Delete
  565. Note that the :meth:`~Model.delete()` method for an object is not
  566. necessarily called when :ref:`deleting objects in bulk using a
  567. QuerySet<topics-db-queries-delete>`. To ensure customized delete logic
  568. gets executed, you can use :data:`~django.db.models.signals.pre_delete`
  569. and/or :data:`~django.db.models.signals.post_delete` signals.
  570. Executing custom SQL
  571. --------------------
  572. Another common pattern is writing custom SQL statements in model methods and
  573. module-level methods. For more details on using raw SQL, see the documentation
  574. on :doc:`using raw SQL</topics/db/sql>`.
  575. .. _model-inheritance:
  576. Model inheritance
  577. =================
  578. Model inheritance in Django works almost identically to the way normal
  579. class inheritance works in Python. The only decision you have to make
  580. is whether you want the parent models to be models in their own right
  581. (with their own database tables), or if the parents are just holders
  582. of common information that will only be visible through the child
  583. models.
  584. There are three styles of inheritance that are possible in Django.
  585. 1. Often, you will just want to use the parent class to hold information that
  586. you don't want to have to type out for each child model. This class isn't
  587. going to ever be used in isolation, so :ref:`abstract-base-classes` are
  588. what you're after.
  589. 2. If you're subclassing an existing model (perhaps something from another
  590. application entirely) and want each model to have its own database table,
  591. :ref:`multi-table-inheritance` is the way to go.
  592. 3. Finally, if you only want to modify the Python-level behavior of a model,
  593. without changing the models fields in any way, you can use
  594. :ref:`proxy-models`.
  595. .. _abstract-base-classes:
  596. Abstract base classes
  597. ---------------------
  598. Abstract base classes are useful when you want to put some common
  599. information into a number of other models. You write your base class
  600. and put ``abstract=True`` in the :ref:`Meta <meta-options>`
  601. class. This model will then not be used to create any database
  602. table. Instead, when it is used as a base class for other models, its
  603. fields will be added to those of the child class. It is an error to
  604. have fields in the abstract base class with the same name as those in
  605. the child (and Django will raise an exception).
  606. An example::
  607. class CommonInfo(models.Model):
  608. name = models.CharField(max_length=100)
  609. age = models.PositiveIntegerField()
  610. class Meta:
  611. abstract = True
  612. class Student(CommonInfo):
  613. home_group = models.CharField(max_length=5)
  614. The ``Student`` model will have three fields: ``name``, ``age`` and
  615. ``home_group``. The ``CommonInfo`` model cannot be used as a normal Django
  616. model, since it is an abstract base class. It does not generate a database
  617. table or have a manager, and cannot be instantiated or saved directly.
  618. For many uses, this type of model inheritance will be exactly what you want.
  619. It provides a way to factor out common information at the Python level, whilst
  620. still only creating one database table per child model at the database level.
  621. ``Meta`` inheritance
  622. ~~~~~~~~~~~~~~~~~~~~
  623. When an abstract base class is created, Django makes any :ref:`Meta <meta-options>`
  624. inner class you declared in the base class available as an
  625. attribute. If a child class does not declare its own :ref:`Meta <meta-options>`
  626. class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to
  627. extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::
  628. class CommonInfo(models.Model):
  629. ...
  630. class Meta:
  631. abstract = True
  632. ordering = ['name']
  633. class Student(CommonInfo):
  634. ...
  635. class Meta(CommonInfo.Meta):
  636. db_table = 'student_info'
  637. Django does make one adjustment to the :ref:`Meta <meta-options>` class of an abstract base
  638. class: before installing the :ref:`Meta <meta-options>` attribute, it sets ``abstract=False``.
  639. This means that children of abstract base classes don't automatically become
  640. abstract classes themselves. Of course, you can make an abstract base class
  641. that inherits from another abstract base class. You just need to remember to
  642. explicitly set ``abstract=True`` each time.
  643. Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an
  644. abstract base class. For example, including ``db_table`` would mean that all
  645. the child classes (the ones that don't specify their own :ref:`Meta <meta-options>`) would use
  646. the same database table, which is almost certainly not what you want.
  647. .. _abstract-related-name:
  648. Be careful with ``related_name``
  649. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  650. If you are using the :attr:`~django.db.models.ForeignKey.related_name` attribute on a ``ForeignKey`` or
  651. ``ManyToManyField``, you must always specify a *unique* reverse name for the
  652. field. This would normally cause a problem in abstract base classes, since the
  653. fields on this class are included into each of the child classes, with exactly
  654. the same values for the attributes (including :attr:`~django.db.models.ForeignKey.related_name`) each time.
  655. .. versionchanged:: 1.2
  656. To work around this problem, when you are using :attr:`~django.db.models.ForeignKey.related_name` in an
  657. abstract base class (only), part of the name should contain
  658. ``'%(app_label)s'`` and ``'%(class)s'``.
  659. - ``'%(class)s'`` is replaced by the lower-cased name of the child class
  660. that the field is used in.
  661. - ``'%(app_label)s'`` is replaced by the lower-cased name of the app the child
  662. class is contained within. Each installed application name must be unique
  663. and the model class names within each app must also be unique, therefore the
  664. resulting name will end up being different.
  665. For example, given an app ``common/``::
  666. class Base(models.Model):
  667. m2m = models.ManyToManyField(OtherModel, related_name="%(app_label)s_%(class)s_related")
  668. class Meta:
  669. abstract = True
  670. class ChildA(Base):
  671. pass
  672. class ChildB(Base):
  673. pass
  674. Along with another app ``rare/``::
  675. from common.models import Base
  676. class ChildB(Base):
  677. pass
  678. The reverse name of the ``commmon.ChildA.m2m`` field will be
  679. ``common_childa_related``, whilst the reverse name of the
  680. ``common.ChildB.m2m`` field will be ``common_childb_related``, and finally the
  681. reverse name of the ``rare.ChildB.m2m`` field will be ``rare_childb_related``.
  682. It is up to you how you use the ``'%(class)s'`` and ``'%(app_label)s`` portion
  683. to construct your related name, but if you forget to use it, Django will raise
  684. errors when you validate your models (or run :djadmin:`syncdb`).
  685. If you don't specify a :attr:`~django.db.models.ForeignKey.related_name`
  686. attribute for a field in an abstract base class, the default reverse name will
  687. be the name of the child class followed by ``'_set'``, just as it normally
  688. would be if you'd declared the field directly on the child class. For example,
  689. in the above code, if the :attr:`~django.db.models.ForeignKey.related_name`
  690. attribute was omitted, the reverse name for the ``m2m`` field would be
  691. ``childa_set`` in the ``ChildA`` case and ``childb_set`` for the ``ChildB``
  692. field.
  693. .. _multi-table-inheritance:
  694. Multi-table inheritance
  695. -----------------------
  696. The second type of model inheritance supported by Django is when each model in
  697. the hierarchy is a model all by itself. Each model corresponds to its own
  698. database table and can be queried and created individually. The inheritance
  699. relationship introduces links between the child model and each of its parents
  700. (via an automatically-created :class:`~django.db.models.OneToOneField`).
  701. For example::
  702. class Place(models.Model):
  703. name = models.CharField(max_length=50)
  704. address = models.CharField(max_length=80)
  705. class Restaurant(Place):
  706. serves_hot_dogs = models.BooleanField()
  707. serves_pizza = models.BooleanField()
  708. All of the fields of ``Place`` will also be available in ``Restaurant``,
  709. although the data will reside in a different database table. So these are both
  710. possible::
  711. >>> Place.objects.filter(name="Bob's Cafe")
  712. >>> Restaurant.objects.filter(name="Bob's Cafe")
  713. If you have a ``Place`` that is also a ``Restaurant``, you can get from the
  714. ``Place`` object to the ``Restaurant`` object by using the lower-case version
  715. of the model name::
  716. >>> p = Place.objects.get(id=12)
  717. # If p is a Restaurant object, this will give the child class:
  718. >>>
  719. <Restaurant: ...>
  720. However, if ``p`` in the above example was *not* a ``Restaurant`` (it had been
  721. created directly as a ``Place`` object or was the parent of some other class),
  722. referring to ```` would raise a Restaurant.DoesNotExist exception.
  723. ``Meta`` and multi-table inheritance
  724. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  725. In the multi-table inheritance situation, it doesn't make sense for a child
  726. class to inherit from its parent's :ref:`Meta <meta-options>` class. All the :ref:`Meta <meta-options>` options
  727. have already been applied to the parent class and applying them again would
  728. normally only lead to contradictory behavior (this is in contrast with the
  729. abstract base class case, where the base class doesn't exist in its own
  730. right).
  731. So a child model does not have access to its parent's :ref:`Meta
  732. <meta-options>` class. However, there are a few limited cases where the child
  733. inherits behavior from the parent: if the child does not specify an
  734. :attr:`~django.db.models.Options.ordering` attribute or a
  735. :attr:`~django.db.models.Options.get_latest_by` attribute, it will inherit
  736. these from its parent.
  737. If the parent has an ordering and you don't want the child to have any natural
  738. ordering, you can explicitly disable it::
  739. class ChildModel(ParentModel):
  740. ...
  741. class Meta:
  742. # Remove parent's ordering effect
  743. ordering = []
  744. Inheritance and reverse relations
  745. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  746. Because multi-table inheritance uses an implicit
  747. :class:`~django.db.models.OneToOneField` to link the child and
  748. the parent, it's possible to move from the parent down to the child,
  749. as in the above example. However, this uses up the name that is the
  750. default :attr:`~django.db.models.ForeignKey.related_name` value for
  751. :class:`~django.db.models.ForeignKey` and
  752. :class:`~django.db.models.ManyToManyField` relations. If you
  753. are putting those types of relations on a subclass of another model,
  754. you **must** specify the
  755. :attr:`~django.db.models.ForeignKey.related_name` attribute on each
  756. such field. If you forget, Django will raise an error when you run
  757. :djadmin:`validate` or :djadmin:`syncdb`.
  758. For example, using the above ``Place`` class again, let's create another
  759. subclass with a :class:`~django.db.models.ManyToManyField`::
  760. class Supplier(Place):
  761. # Must specify related_name on all relations.
  762. customers = models.ManyToManyField(Restaurant, related_name='provider')
  763. Specifying the parent link field
  764. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  765. As mentioned, Django will automatically create a
  766. :class:`~django.db.models.OneToOneField` linking your child
  767. class back any non-abstract parent models. If you want to control the
  768. name of the attribute linking back to the parent, you can create your
  769. own :class:`~django.db.models.OneToOneField` and set
  770. :attr:`parent_link=True <django.db.models.OneToOneField.parent_link>`
  771. to indicate that your field is the link back to the parent class.
  772. .. _proxy-models:
  773. Proxy models
  774. ------------
  775. When using :ref:`multi-table inheritance <multi-table-inheritance>`, a new
  776. database table is created for each subclass of a model. This is usually the
  777. desired behavior, since the subclass needs a place to store any additional
  778. data fields that are not present on the base class. Sometimes, however, you
  779. only want to change the Python behavior of a model -- perhaps to change the
  780. default manager, or add a new method.
  781. This is what proxy model inheritance is for: creating a *proxy* for the
  782. original model. You can create, delete and update instances of the proxy model
  783. and all the data will be saved as if you were using the original (non-proxied)
  784. model. The difference is that you can change things like the default model
  785. ordering or the default manager in the proxy, without having to alter the
  786. original.
  787. Proxy models are declared like normal models. You tell Django that it's a
  788. proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of
  789. the ``Meta`` class to ``True``.
  790. For example, suppose you want to add a method to the standard
  791. :class:`~django.contrib.auth.models.User` model that will be used in your
  792. templates. You can do it like this::
  793. from django.contrib.auth.models import User
  794. class MyUser(User):
  795. class Meta:
  796. proxy = True
  797. def do_something(self):
  798. ...
  799. The ``MyUser`` class operates on the same database table as its parent
  800. :class:`~django.contrib.auth.models.User` class. In particular, any new
  801. instances of :class:`~django.contrib.auth.models.User` will also be accessible
  802. through ``MyUser``, and vice-versa::
  803. >>> u = User.objects.create(username="foobar")
  804. >>> MyUser.objects.get(username="foobar")
  805. <MyUser: foobar>
  806. You could also use a proxy model to define a different default ordering on a
  807. model. The standard :class:`~django.contrib.auth.models.User` model has no
  808. ordering defined on it (intentionally; sorting is expensive and we don't want
  809. to do it all the time when we fetch users). You might want to regularly order
  810. by the ``username`` attribute when you use the proxy. This is easy::
  811. class OrderedUser(User):
  812. class Meta:
  813. ordering = ["username"]
  814. proxy = True
  815. Now normal :class:`~django.contrib.auth.models.User` queries will be unordered
  816. and ``OrderedUser`` queries will be ordered by ``username``.
  817. QuerySets still return the model that was requested
  818. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  819. There is no way to have Django return, say, a ``MyUser`` object whenever you
  820. query for :class:`~django.contrib.auth.models.User` objects. A queryset for
  821. ``User`` objects will return those types of objects. The whole point of proxy
  822. objects is that code relying on the original ``User`` will use those and your
  823. own code can use the extensions you included (that no other code is relying on
  824. anyway). It is not a way to replace the ``User`` (or any other) model
  825. everywhere with something of your own creation.
  826. Base class restrictions
  827. ~~~~~~~~~~~~~~~~~~~~~~~
  828. A proxy model must inherit from exactly one non-abstract model class. You
  829. can't inherit from multiple non-abstract models as the proxy model doesn't
  830. provide any connection between the rows in the different database tables. A
  831. proxy model can inherit from any number of abstract model classes, providing
  832. they do *not* define any model fields.
  833. Proxy models inherit any ``Meta`` options that they don't define from their
  834. non-abstract model parent (the model they are proxying for).
  835. Proxy model managers
  836. ~~~~~~~~~~~~~~~~~~~~
  837. If you don't specify any model managers on a proxy model, it inherits the
  838. managers from its model parents. If you define a manager on the proxy model,
  839. it will become the default, although any managers defined on the parent
  840. classes will still be available.
  841. Continuing our example from above, you could change the default manager used
  842. when you query the ``User`` model like this::
  843. class NewManager(models.Manager):
  844. ...
  845. class MyUser(User):
  846. objects = NewManager()
  847. class Meta:
  848. proxy = True
  849. If you wanted to add a new manager to the Proxy, without replacing the
  850. existing default, you can use the techniques described in the :ref:`custom
  851. manager <custom-managers-and-inheritance>` documentation: create a base class
  852. containing the new managers and inherit that after the primary base class::
  853. # Create an abstract class for the new manager.
  854. class ExtraManagers(models.Model):
  855. secondary = NewManager()
  856. class Meta:
  857. abstract = True
  858. class MyUser(User, ExtraManagers):
  859. class Meta:
  860. proxy = True
  861. You probably won't need to do this very often, but, when you do, it's
  862. possible.
  863. .. _proxy-vs-unmanaged-models:
  864. Differences between proxy inheritance and unmanaged models
  865. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  866. Proxy model inheritance might look fairly similar to creating an unmanaged
  867. model, using the :attr:`~django.db.models.Options.managed` attribute on a
  868. model's ``Meta`` class. The two alternatives are not quite the same and it's
  869. worth considering which one you should use.
  870. One difference is that you can (and, in fact, must unless you want an empty
  871. model) specify model fields on models with ``Meta.managed=False``. You could,
  872. with careful setting of :attr:`Meta.db_table
  873. <django.db.models.Options.db_table>` create an unmanaged model that shadowed
  874. an existing model and add Python methods to it. However, that would be very
  875. repetitive and fragile as you need to keep both copies synchronized if you
  876. make any changes.
  877. The other difference that is more important for proxy models, is how model
  878. managers are handled. Proxy models are intended to behave exactly like the
  879. model they are proxying for. So they inherit the parent model's managers,
  880. including the default manager. In the normal multi-table model inheritance
  881. case, children do not inherit managers from their parents as the custom
  882. managers aren't always appropriate when extra fields are involved. The
  883. :ref:`manager documentation <custom-managers-and-inheritance>` has more
  884. details about this latter case.
  885. When these two features were implemented, attempts were made to squash them
  886. into a single option. It turned out that interactions with inheritance, in
  887. general, and managers, in particular, made the API very complicated and
  888. potentially difficult to understand and use. It turned out that two options
  889. were needed in any case, so the current separation arose.
  890. So, the general rules are:
  891. 1. If you are mirroring an existing model or database table and don't want
  892. all the original database table columns, use ``Meta.managed=False``.
  893. That option is normally useful for modeling database views and tables
  894. not under the control of Django.
  895. 2. If you are wanting to change the Python-only behavior of a model, but
  896. keep all the same fields as in the original, use ``Meta.proxy=True``.
  897. This sets things up so that the proxy model is an exact copy of the
  898. storage structure of the original model when data is saved.
  899. Multiple inheritance
  900. --------------------
  901. Just as with Python's subclassing, it's possible for a Django model to inherit
  902. from multiple parent models. Keep in mind that normal Python name resolution
  903. rules apply. The first base class that a particular name (e.g. :ref:`Meta
  904. <meta-options>`) appears in will be the one that is used; for example, this
  905. means that if multiple parents contain a :ref:`Meta <meta-options>` class,
  906. only the first one is going to be used, and all others will be ignored.
  907. Generally, you won't need to inherit from multiple parents. The main use-case
  908. where this is useful is for "mix-in" classes: adding a particular extra
  909. field or method to every class that inherits the mix-in. Try to keep your
  910. inheritance hierarchies as simple and straightforward as possible so that you
  911. won't have to struggle to work out where a particular piece of information is
  912. coming from.
  913. Field name "hiding" is not permitted
  914. -------------------------------------
  915. In normal Python class inheritance, it is permissible for a child class to
  916. override any attribute from the parent class. In Django, this is not permitted
  917. for attributes that are :class:`~django.db.models.Field` instances (at
  918. least, not at the moment). If a base class has a field called ``author``, you
  919. cannot create another model field called ``author`` in any class that inherits
  920. from that base class.
  921. Overriding fields in a parent model leads to difficulties in areas such as
  922. initializing new instances (specifying which field is being initialized in
  923. ``Model.__init__``) and serialization. These are features which normal Python
  924. class inheritance doesn't have to deal with in quite the same way, so the
  925. difference between Django model inheritance and Python class inheritance isn't
  926. arbitrary.
  927. This restriction only applies to attributes which are
  928. :class:`~django.db.models.Field` instances. Normal Python attributes
  929. can be overridden if you wish. It also only applies to the name of the
  930. attribute as Python sees it: if you are manually specifying the database
  931. column name, you can have the same column name appearing in both a child and
  932. an ancestor model for multi-table inheritance (they are columns in two
  933. different database tables).
  934. Django will raise a :exc:`~django.core.exceptions.FieldError` if you override
  935. any model field in any ancestor model.