models.txt 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. .. _topics-db-models:
  2. ==============
  3. Writing models
  4. ==============
  5. .. module:: django.db.models
  6. A model is the single, definitive source of data about your data. It contains
  7. the essential fields and behaviors of the data you're storing. Generally, each
  8. model maps to a single database table.
  9. The basics:
  10. * Each model is a Python class that subclasses
  11. :class:`django.db.models.Model`.
  12. * Each attribute of the model represents a database field.
  13. * With all of this, Django gives you an automatically-generated
  14. database-access API; see :ref:`topics-db-queries`.
  15. .. seealso::
  16. A companion to this document is the `official repository of model
  17. examples`_. (In the Django source distribution, these examples are in the
  18. ``tests/modeltests`` directory.)
  19. .. _official repository of model examples: http://www.djangoproject.com/documentation/models/
  20. Quick example
  21. =============
  22. This example model defines a ``Person``, which has a ``first_name`` and
  23. ``last_name``::
  24. from django.db import models
  25. class Person(models.Model):
  26. first_name = models.CharField(max_length=30)
  27. last_name = models.CharField(max_length=30)
  28. ``first_name`` and ``last_name`` are fields_ of the model. Each field is
  29. specified as a class attribute, and each attribute maps to a database column.
  30. The above ``Person`` model would create a database table like this:
  31. .. code-block:: sql
  32. CREATE TABLE myapp_person (
  33. "id" serial NOT NULL PRIMARY KEY,
  34. "first_name" varchar(30) NOT NULL,
  35. "last_name" varchar(30) NOT NULL
  36. );
  37. Some technical notes:
  38. * The name of the table, ``myapp_person``, is automatically derived from
  39. some model metadata but can be overridden. See :ref:`table-names` for more
  40. details..
  41. * An ``id`` field is added automatically, but this behavior can be
  42. overridden. See :ref:`automatic-primary-key-fields`.
  43. * The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL
  44. syntax, but it's worth noting Django uses SQL tailored to the database
  45. backend specified in your :ref:`settings file <topics-settings>`.
  46. Using models
  47. ============
  48. Once you have defined your models, you need to tell Django you're going to *use*
  49. those models. Do this by editing your settings file and changing the
  50. :setting:`INSTALLED_APPS` setting to add the name of the module that contains
  51. your ``models.py``.
  52. For example, if the models for your application live in the module
  53. ``mysite.myapp.models`` (the package structure that is created for an
  54. application by the :djadmin:`manage.py startapp <startapp>` script),
  55. :setting:`INSTALLED_APPS` should read, in part::
  56. INSTALLED_APPS = (
  57. #...
  58. 'mysite.myapp',
  59. #...
  60. )
  61. When you add new apps to :setting:`INSTALLED_APPS`, be sure to run
  62. :djadmin:`manage.py syncdb <syncdb>`.
  63. Fields
  64. ======
  65. The most important part of a model -- and the only required part of a model --
  66. is the list of database fields it defines. Fields are specified by class
  67. attributes.
  68. Example::
  69. class Musician(models.Model):
  70. first_name = models.CharField(max_length=50)
  71. last_name = models.CharField(max_length=50)
  72. instrument = models.CharField(max_length=100)
  73. class Album(models.Model):
  74. artist = models.ForeignKey(Musician)
  75. name = models.CharField(max_length=100)
  76. release_date = models.DateField()
  77. num_stars = models.IntegerField()
  78. Field types
  79. -----------
  80. Each field in your model should be an instance of the appropriate
  81. :class:`~django.db.models.Field` class. Django uses the field class types to
  82. determine a few things:
  83. * The database column type (e.g. ``INTEGER``, ``VARCHAR``).
  84. * The widget to use in Django's admin interface, if you care to use it
  85. (e.g. ``<input type="text">``, ``<select>``).
  86. * The minimal validation requirements, used in Django's admin and in
  87. automatically-generated forms.
  88. Django ships with dozens of built-in field types; you can find the complete list
  89. in the :ref:`model field reference <model-field-types>`. You can easily write
  90. your own fields if Django's built-in ones don't do the trick; see
  91. :ref:`howto-custom-model-fields`.
  92. Field options
  93. -------------
  94. Each field takes a certain set of field-specific arguments (documented in the
  95. :ref:`model field reference <model-field-types>`). For example,
  96. :class:`~django.db.models.CharField` (and its subclasses) require a
  97. :attr:`~django.db.models.CharField.max_length` argument which specifies the size
  98. of the ``VARCHAR`` database field used to store the data.
  99. There's also a set of common arguments available to all field types. All are
  100. optional. They're fully explained in the :ref:`reference
  101. <common-model-field-options>`, but here's a quick summary of the most often-used
  102. ones:
  103. :attr:`~Field.null`
  104. If ``True``, Django will store empty values as ``NULL`` in the database.
  105. Default is ``False``.
  106. :attr:`~Field.blank`
  107. If ``True``, the field is allowed to be blank. Default is ``False``.
  108. Note that this is different than :attr:`~Field.null`.
  109. :attr:`~Field.null` is purely database-related, whereas
  110. :attr:`~Field.blank` is validation-related. If a field has
  111. :attr:`blank=True <Field.blank>`, validation on Django's admin site will
  112. allow entry of an empty value. If a field has :attr:`blank=False
  113. <Field.blank>`, the field will be required.
  114. :attr:`~Field.choices`
  115. An iterable (e.g., a list or tuple) of 2-tuples to use as choices for
  116. this field. If this is given, Django's admin will use a select box
  117. instead of the standard text field and will limit choices to the choices
  118. given.
  119. A choices list looks like this::
  120. YEAR_IN_SCHOOL_CHOICES = (
  121. ('FR', 'Freshman'),
  122. ('SO', 'Sophomore'),
  123. ('JR', 'Junior'),
  124. ('SR', 'Senior'),
  125. ('GR', 'Graduate'),
  126. )
  127. :attr:`~Field.default`
  128. The default value for the field. This can be a value or a callable
  129. object. If callable it will be called every time a new object is
  130. created.
  131. :attr:`~Field.help_text`
  132. Extra "help" text to be displayed under the field on the object's admin
  133. form. It's useful for documentation even if your object doesn't have an
  134. admin form.
  135. :attr:`~Field.primary_key`
  136. If ``True``, this field is the primary key for the model.
  137. If you don't specify :attr:`primary_key=True <Field.primary_key>` for
  138. any fields in your model, Django will automatically add an
  139. :class:`IntegerField` to hold the primary key, so you don't need to set
  140. :attr:`primary_key=True <Field.primary_key>` on any of your fields
  141. unless you want to override the default primary-key behavior. For more,
  142. see :ref:`automatic-primary-key-fields`.
  143. :attr:`~Field.unique`
  144. If ``True``, this field must be unique throughout the table.
  145. Again, these are just short descriptions of the most common field options. Full
  146. details can be found in the :ref:`common model field option reference
  147. <common-model-field-options>`.
  148. .. _automatic-primary-key-fields:
  149. Automatic primary key fields
  150. ----------------------------
  151. By default, Django gives each model the following field::
  152. id = models.AutoField(primary_key=True)
  153. This is an auto-incrementing primary key.
  154. If you'd like to specify a custom primary key, just specify
  155. :attr:`primary_key=True <Field.primary_key>` on one of your fields. If Django
  156. sees you've explicitly set :attr:`Field.primary_key`, it won't add the automatic
  157. ``id`` column.
  158. Each model requires exactly one field to have :attr:`primary_key=True
  159. <Field.primary_key>`.
  160. Verbose field names
  161. -------------------
  162. Each field type, except for :class:`~django.db.models.ForeignKey`,
  163. :class:`~django.db.models.ManyToManyField` and
  164. :class:`~django.db.models.OneToOneField`, takes an optional first positional
  165. argument -- a verbose name. If the verbose name isn't given, Django will
  166. automatically create it using the field's attribute name, converting underscores
  167. to spaces.
  168. In this example, the verbose name is ``"Person's first name"``::
  169. first_name = models.CharField("Person's first name", max_length=30)
  170. In this example, the verbose name is ``"first name"``::
  171. first_name = models.CharField(max_length=30)
  172. :class:`~django.db.models.ForeignKey`,
  173. :class:`~django.db.models.ManyToManyField` and
  174. :class:`~django.db.models.OneToOneField` require the first argument to be a
  175. model class, so use the :attr:`~Field.verbose_name` keyword argument::
  176. poll = models.ForeignKey(Poll, verbose_name="the related poll")
  177. sites = models.ManyToManyField(Site, verbose_name="list of sites")
  178. place = models.OneToOneField(Place, verbose_name="related place")
  179. The convention is not to capitalize the first letter of the
  180. :attr:`~Field.verbose_name`. Django will automatically capitalize the first
  181. letter where it needs to.
  182. Relationships
  183. -------------
  184. Clearly, the power of relational databases lies in relating tables to each
  185. other. Django offers ways to define the three most common types of database
  186. relationships: many-to-one, many-to-many and one-to-one.
  187. Many-to-one relationships
  188. ~~~~~~~~~~~~~~~~~~~~~~~~~
  189. To define a many-to-one relationship, use :class:`~django.db.models.ForeignKey`.
  190. You use it just like any other :class:`~django.db.models.Field` type: by
  191. including it as a class attribute of your model.
  192. :class:`~django.db.models.ForeignKey` requires a positional argument: the class
  193. to which the model is related.
  194. For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
  195. ``Manufacturer`` makes multiple cars but each ``Car`` only has one
  196. ``Manufacturer`` -- use the following definitions::
  197. class Manufacturer(models.Model):
  198. # ...
  199. class Car(models.Model):
  200. manufacturer = models.ForeignKey(Manufacturer)
  201. # ...
  202. You can also create :ref:`recursive relationships <recursive-relationships>` (an
  203. object with a many-to-one relationship to itself) and :ref:`relationships to
  204. models not yet defined <lazy-relationships>`; see :ref:`the model field
  205. reference <ref-foreignkey>` for details.
  206. It's suggested, but not required, that the name of a
  207. :class:`~django.db.models.ForeignKey` field (``manufacturer`` in the example
  208. above) be the name of the model, lowercase. You can, of course, call the field
  209. whatever you want. For example::
  210. class Car(models.Model):
  211. company_that_makes_it = models.ForeignKey(Manufacturer)
  212. # ...
  213. .. seealso::
  214. See the `Many-to-one relationship model example`_ for a full example.
  215. .. _Many-to-one relationship model example: http://www.djangoproject.com/documentation/models/many_to_one/
  216. :class:`~django.db.models.ForeignKey` fields also accept a number of extra
  217. arguments which are explained in :ref:`the model field reference
  218. <foreign-key-arguments>`. These options help define how the relationship should
  219. work; all are optional.
  220. Many-to-many relationships
  221. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  222. To define a many-to-many relationship, use
  223. :class:`~django.db.models.ManyToManyField`. You use it just like any other
  224. :class:`~django.db.models.Field` type: by including it as a class attribute of
  225. your model.
  226. :class:`~django.db.models.ManyToManyField` requires a positional argument: the
  227. class to which the model is related.
  228. For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
  229. ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings
  230. -- here's how you'd represent that::
  231. class Topping(models.Model):
  232. # ...
  233. class Pizza(models.Model):
  234. # ...
  235. toppings = models.ManyToManyField(Topping)
  236. As with :class:`~django.db.models.ForeignKey`, you can also create
  237. :ref:`recursive relationships <recursive-relationships>` (an object with a
  238. many-to-one relationship to itself) and :ref:`relationships to models not yet
  239. defined <lazy-relationships>`; see :ref:`the model field reference
  240. <ref-manytomany>` for details.
  241. It's suggested, but not required, that the name of a
  242. :class:`~django.db.models.ManyToManyField` (``toppings`` in the example above)
  243. be a plural describing the set of related model objects.
  244. It doesn't matter which model gets the
  245. :class:`~django.db.models.ManyToManyField`, but you only need it in one of the
  246. models -- not in both.
  247. Generally, :class:`~django.db.models.ManyToManyField` instances should go in the
  248. object that's going to be edited in the admin interface, if you're using
  249. Django's admin. In the above example, ``toppings`` is in ``Pizza`` (rather than
  250. ``Topping`` having a ``pizzas`` :class:`~django.db.models.ManyToManyField` )
  251. because it's more natural to think about a ``Pizza`` having toppings than a
  252. topping being on multiple pizzas. The way it's set up above, the ``Pizza`` admin
  253. form would let users select the toppings.
  254. .. seealso::
  255. See the `Many-to-many relationship model example`_ for a full example.
  256. .. _Many-to-many relationship model example: http://www.djangoproject.com/documentation/models/many_to_many/
  257. :class:`~django.db.models.ManyToManyField` fields also accept a number of extra
  258. arguments which are explained in :ref:`the model field reference
  259. <manytomany-arguments>`. These options help define how the relationship should
  260. work; all are optional.
  261. Extra fields on many-to-many relationships
  262. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  263. .. versionadded:: 1.0
  264. When you're only dealing with simple many-to-many relationships such as
  265. mixing and matching pizzas and toppings, a standard :class:`~django.db.models.ManyToManyField` is all you need. However, sometimes
  266. you may need to associate data with the relationship between two models.
  267. For example, consider the case of an application tracking the musical groups
  268. which musicians belong to. There is a many-to-many relationship between a person
  269. and the groups of which they are a member, so you could use a
  270. :class:`~django.db.models.ManyToManyField` to represent this relationship.
  271. However, there is a lot of detail about the membership that you might want to
  272. collect, such as the date at which the person joined the group.
  273. For these situations, Django allows you to specify the model that will be used
  274. to govern the many-to-many relationship. You can then put extra fields on the
  275. intermediate model. The intermediate model is associated with the
  276. :class:`~django.db.models.ManyToManyField` using the
  277. :attr:`through <ManyToManyFields.through>` argument to point to the model
  278. that will act as an intermediary. For our musician example, the code would look
  279. something like this::
  280. class Person(models.Model):
  281. name = models.CharField(max_length=128)
  282. def __unicode__(self):
  283. return self.name
  284. class Group(models.Model):
  285. name = models.CharField(max_length=128)
  286. members = models.ManyToManyField(Person, through='Membership')
  287. def __unicode__(self):
  288. return self.name
  289. class Membership(models.Model):
  290. person = models.ForeignKey(Person)
  291. group = models.ForeignKey(Group)
  292. date_joined = models.DateField()
  293. invite_reason = models.CharField(max_length=64)
  294. When you set up the intermediary model, you explicitly specify foreign
  295. keys to the models that are involved in the ManyToMany relation. This
  296. explicit declaration defines how the two models are related.
  297. There are a few restrictions on the intermediate model:
  298. * Your intermediate model must contain one - and *only* one - foreign key
  299. on the target model (this would be ``Person`` in our example). If you
  300. have more than one foreign key, a validation error will be raised.
  301. * Your intermediate model must contain one - and *only* one - foreign key
  302. on the source model (this would be ``Group`` in our example). If you
  303. have more than one foreign key, a validation error will be raised.
  304. * The only exception to this is a model which has a many-to-many
  305. relationship to itself, through an intermediary model. In this
  306. case, two foreign keys to the same model are permitted, but they
  307. will be treated as the two (different) sides of the many-to-many
  308. relation.
  309. * When defining a many-to-many relationship from a model to
  310. itself, using an intermediary model, you *must* use
  311. :attr:`symmetrical=False <ManyToManyFields.symmetrical>` (see
  312. :ref:`the model field reference <manytomany-arguments>`).
  313. Now that you have set up your :class:`~django.db.models.ManyToManyField` to use
  314. your intermediary model (Membership, in this case), you're ready to start
  315. creating some many-to-many relationships. You do this by creating instances of
  316. the intermediate model::
  317. >>> ringo = Person.objects.create(name="Ringo Starr")
  318. >>> paul = Person.objects.create(name="Paul McCartney")
  319. >>> beatles = Group.objects.create(name="The Beatles")
  320. >>> m1 = Membership(person=ringo, group=beatles,
  321. ... date_joined=date(1962, 8, 16),
  322. ... invite_reason= "Needed a new drummer.")
  323. >>> m1.save()
  324. >>> beatles.members.all()
  325. [<Person: Ringo Starr>]
  326. >>> ringo.group_set.all()
  327. [<Group: The Beatles>]
  328. >>> m2 = Membership.objects.create(person=paul, group=beatles,
  329. ... date_joined=date(1960, 8, 1),
  330. ... invite_reason= "Wanted to form a band.")
  331. >>> beatles.members.all()
  332. [<Person: Ringo Starr>, <Person: Paul McCartney>]
  333. Unlike normal many-to-many fields, you *can't* use ``add``, ``create``,
  334. or assignment (i.e., ``beatles.members = [...]``) to create relationships::
  335. # THIS WILL NOT WORK
  336. >>> beatles.members.add(john)
  337. # NEITHER WILL THIS
  338. >>> beatles.members.create(name="George Harrison")
  339. # AND NEITHER WILL THIS
  340. >>> beatles.members = [john, paul, ringo, george]
  341. Why? You can't just create a relationship between a Person and a Group - you
  342. need to specify all the detail for the relationship required by the
  343. Membership table. The simple ``add``, ``create`` and assignment calls
  344. don't provide a way to specify this extra detail. As a result, they are
  345. disabled for many-to-many relationships that use an intermediate model.
  346. The only way to create a many-to-many relationship with an intermediate table
  347. is to create instances of the intermediate model.
  348. The ``remove`` method is disabled for similar reasons. However, the
  349. ``clear()`` method can be used to remove all many-to-many relationships
  350. for an instance::
  351. # Beatles have broken up
  352. >>> beatles.members.clear()
  353. Once you have established the many-to-many relationships by creating instances
  354. of your intermediate model, you can issue queries. Just as with normal
  355. many-to-many relationships, you can query using the attributes of the
  356. many-to-many-related model::
  357. # Find all the groups with a member whose name starts with 'Paul'
  358. >>> Groups.objects.filter(person__name__startswith='Paul')
  359. [<Group: The Beatles>]
  360. As you are using an intermediate table, you can also query on the attributes
  361. of the intermediate model::
  362. # Find all the members of the Beatles that joined after 1 Jan 1961
  363. >>> Person.objects.filter(
  364. ... group__name='The Beatles',
  365. ... membership__date_joined__gt=date(1961,1,1))
  366. [<Person: Ringo Starr]
  367. One-to-one relationships
  368. ~~~~~~~~~~~~~~~~~~~~~~~~
  369. To define a one-to-one relationship, use
  370. :class:`~django.db.models.OneToOneField`. You use it just like any other
  371. ``Field`` type: by including it as a class attribute of your model.
  372. This is most useful on the primary key of an object when that object "extends"
  373. another object in some way.
  374. :class:`~django.db.models.OneToOneField` requires a positional argument: the
  375. class to which the model is related.
  376. For example, if you were building a database of "places", you would
  377. build pretty standard stuff such as address, phone number, etc. in the
  378. database. Then, if you wanted to build a database of restaurants on
  379. top of the places, instead of repeating yourself and replicating those
  380. fields in the ``Restaurant`` model, you could make ``Restaurant`` have
  381. a :class:`~django.db.models.OneToOneField` to ``Place`` (because a
  382. restaurant "is a" place; in fact, to handle this you'd typically use
  383. :ref:`inheritance <model-inheritance>`, which involves an implicit
  384. one-to-one relation).
  385. As with :class:`~django.db.models.ForeignKey`, a
  386. :ref:`recursive relationship <recursive-relationships>`
  387. can be defined and
  388. :ref:`references to as-yet undefined models <lazy-relationships>`
  389. can be made; see
  390. :class:`the model field reference <django.db.models.fields.OneToOneField>`
  391. for details.
  392. .. seealso::
  393. See the `One-to-one relationship model example`_ for a full example.
  394. .. _One-to-one relationship model example: http://www.djangoproject.com/documentation/models/one_to_one/
  395. **New in Django development version**
  396. :class:`~django.db.models.OneToOneField` fields also accept one optional argument
  397. described in the :ref:`model field reference <ref-onetoone>`.
  398. :class:`~django.db.models.OneToOneField` classes used to automatically become
  399. the primary key on a model. This is no longer true (although you can manually
  400. pass in the :attr:`~django.db.models.Field.primary_key` argument if you like).
  401. Thus, it's now possible to have multiple fields of type
  402. :class:`~django.db.models.OneToOneField` on a single model.
  403. Models across files
  404. -------------------
  405. It's perfectly OK to relate a model to one from another app. To do this, just
  406. import the related model at the top of the model that holds your model. Then,
  407. just refer to the other model class wherever needed. For example::
  408. from mysite.geography.models import ZipCode
  409. class Restaurant(models.Model):
  410. # ...
  411. zip_code = models.ForeignKey(ZipCode)
  412. Field name restrictions
  413. -----------------------
  414. Django places only two restrictions on model field names:
  415. 1. A field name cannot be a Python reserved word, because that would result
  416. in a Python syntax error. For example::
  417. class Example(models.Model):
  418. pass = models.IntegerField() # 'pass' is a reserved word!
  419. 2. A field name cannot contain more than one underscore in a row, due to
  420. the way Django's query lookup syntax works. For example::
  421. class Example(models.Model):
  422. foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
  423. These limitations can be worked around, though, because your field name doesn't
  424. necessarily have to match your database column name. See the
  425. :attr:`~Field.db_column` option.
  426. SQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as
  427. model field names, because Django escapes all database table names and column
  428. names in every underlying SQL query. It uses the quoting syntax of your
  429. particular database engine.
  430. Custom field types
  431. ------------------
  432. .. versionadded:: 1.0
  433. If one of the existing model fields cannot be used to fit your purposes, or if
  434. you wish to take advantage of some less common database column types, you can
  435. create your own field class. Full coverage of creating your own fields is
  436. provided in :ref:`howto-custom-model-fields`.
  437. .. _meta-options:
  438. Meta options
  439. ============
  440. Give your model metadata by using an inner ``class Meta``, like so::
  441. class Ox(models.Model):
  442. horn_length = models.IntegerField()
  443. class Meta:
  444. ordering = ["horn_length"]
  445. verbose_name_plural = "oxen"
  446. Model metadata is "anything that's not a field", such as ordering options
  447. (:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), or
  448. human-readable singular and plural names (:attr:`~Options.verbose_name` and
  449. :attr:`~Options.verbose_name_plural`). None are required, and adding ``class
  450. Meta`` to a model is completely optional.
  451. A complete list of all possible ``Meta`` options can be found in the :ref:`model
  452. option reference <ref-models-options>`.
  453. .. _model-methods:
  454. Model methods
  455. =============
  456. Define custom methods on a model to add custom "row-level" functionality to your
  457. objects. Whereas :class:`~django.db.models.Manager` methods are intended to do
  458. "table-wide" things, model methods should act on a particular model instance.
  459. This is a valuable technique for keeping business logic in one place -- the
  460. model.
  461. For example, this model has a few custom methods::
  462. from django.contrib.localflavor.us.models import USStateField
  463. class Person(models.Model):
  464. first_name = models.CharField(max_length=50)
  465. last_name = models.CharField(max_length=50)
  466. birth_date = models.DateField()
  467. address = models.CharField(max_length=100)
  468. city = models.CharField(max_length=50)
  469. state = USStateField() # Yes, this is America-centric...
  470. def baby_boomer_status(self):
  471. "Returns the person's baby-boomer status."
  472. import datetime
  473. if datetime.date(1945, 8, 1) <= self.birth_date <= datetime.date(1964, 12, 31):
  474. return "Baby boomer"
  475. if self.birth_date < datetime.date(1945, 8, 1):
  476. return "Pre-boomer"
  477. return "Post-boomer"
  478. def is_midwestern(self):
  479. "Returns True if this person is from the Midwest."
  480. return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')
  481. def _get_full_name(self):
  482. "Returns the person's full name."
  483. return '%s %s' % (self.first_name, self.last_name)
  484. full_name = property(_get_full_name)
  485. The last method in this example is a :term:`property`. `Read more about
  486. properties`_.
  487. .. _Read more about properties: http://www.python.org/download/releases/2.2/descrintro/#property
  488. The :ref:`model instance reference <ref-models-instances>` has a complete list
  489. of :ref:`methods automatically given to each model <model-instance-methods>`.
  490. You can override most of these -- see `overriding predefined model methods`_,
  491. below -- but there are a couple that you'll almost always want to define:
  492. :meth:`~Model.__unicode__`
  493. A Python "magic method" that returns a unicode "representation" of any
  494. object. This is what Python and Django will use whenever a model
  495. instance needs to be coerced and displayed as a plain string. Most
  496. notably, this happens when you display an object in an interactive
  497. console or in the admin.
  498. You'll always want to define this method; the default isn't very helpful
  499. at all.
  500. :meth:`~Model.get_absolute_url`
  501. This tells Django how to calculate the URL for an object. Django uses
  502. this in its admin interface, and any time it needs to figure out a URL
  503. for an object.
  504. Any object that has a URL that uniquely identifies it should define this
  505. method.
  506. Overriding predefined model methods
  507. -----------------------------------
  508. There's another set of :ref:`model methods <model-instance-methods>` that
  509. encapsulate a bunch of database behavior that you'll want to customize. In
  510. particular you'll often want to change the way :meth:`~Model.save` and
  511. :meth:`~Model.delete` work.
  512. You're free to override these methods (and any other model method) to alter
  513. behavior.
  514. A classic use-case for overriding the built-in methods is if you want something
  515. to happen whenever you save an object. For example (see
  516. :meth:`~Model.save` for documentation of the parameters it accepts)::
  517. class Blog(models.Model):
  518. name = models.CharField(max_length=100)
  519. tagline = models.TextField()
  520. def save(self, force_insert=False, force_update=False):
  521. do_something()
  522. super(Blog, self).save(force_insert, force_update) # Call the "real" save() method.
  523. do_something_else()
  524. You can also prevent saving::
  525. class Blog(models.Model):
  526. name = models.CharField(max_length=100)
  527. tagline = models.TextField()
  528. def save(self, force_insert=False, force_update=False):
  529. if self.name == "Yoko Ono's blog":
  530. return # Yoko shall never have her own blog!
  531. else:
  532. super(Blog, self).save(force_insert, force_update) # Call the "real" save() method.
  533. It's important to remember to call the superclass method -- that's that
  534. ``super(Blog, self).save()`` business -- to ensure that the object still gets
  535. saved into the database. If you forget to call the superclass method, the
  536. default behavior won't happen and the database won't get touched.
  537. Executing custom SQL
  538. --------------------
  539. Another common pattern is writing custom SQL statements in model methods and
  540. module-level methods. The object :class:`django.db.connection
  541. <django.db.backends.DatabaseWrapper>` represents the current database
  542. connection. To use it, call :meth:`connection.cursor()
  543. <django.db.backends.DatabaseWrapper.cursor>` to get a cursor object. Then, call
  544. ``cursor.execute(sql, [params])`` to execute the SQL and
  545. :meth:`cursor.fetchone() <django.db.backends.CursorWrapper.fetchone>` or
  546. :meth:`cursor.fetchall() <django.db.backends.CursorWrapper.fetchall>` to return
  547. the resulting rows. For example::
  548. def my_custom_sql(self):
  549. from django.db import connection
  550. cursor = connection.cursor()
  551. cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
  552. row = cursor.fetchone()
  553. return row
  554. :class:`connection <django.db.backends.DatabaseWrapper>` and
  555. :class:`<django.db.backends.CursorWrapper>` mostly implement the standard Python
  556. DB-API -- see :pep:`249` -- with the addition of Django's :ref:`transaction
  557. handling <topics-db-transactions>`. If you're not familiar with the Python
  558. DB-API, note that the SQL statement in :meth:`cursor.execute()
  559. <django.db.backends.CursorWrapper.execute>` uses placeholders, ``"%s"``, rather
  560. than adding parameters directly within the SQL. If you use this technique, the
  561. underlying database library will automatically add quotes and escaping to your
  562. parameter(s) as necessary. (Also note that Django expects the ``"%s"``
  563. placeholder, *not* the ``"?"`` placeholder, which is used by the SQLite Python
  564. bindings. This is for the sake of consistency and sanity.)
  565. A final note: If all you want to do is a custom ``WHERE`` clause, you can use
  566. the :meth:`~QuerySet.extra` lookup method, which lets you add custom SQL to a
  567. query.
  568. .. _model-inheritance:
  569. Model inheritance
  570. =================
  571. .. versionadded:: 1.0
  572. Model inheritance in Django works almost identically to the way normal
  573. class inheritance works in Python. The only decision you have to make
  574. is whether you want the parent models to be models in their own right
  575. (with their own database tables), or if the parents are just holders
  576. of common information that will only be visible through the child
  577. models.
  578. Often, you will just want to use the parent class to hold information
  579. that you don't want to have to type out for each child model. This
  580. class isn't going to ever be used in isolation, so
  581. :ref:`abstract-base-classes` are what you're after. However, if you're
  582. subclassing an existing model (perhaps something from another
  583. application entirely), or want each model to have its own database
  584. table, :ref:`multi-table-inheritance` is the way to go.
  585. .. _abstract-base-classes:
  586. Abstract base classes
  587. ---------------------
  588. Abstract base classes are useful when you want to put some common
  589. information into a number of other models. You write your base class
  590. and put ``abstract=True`` in the :ref:`Meta <meta-options>`
  591. class. This model will then not be used to create any database
  592. table. Instead, when it is used as a base class for other models, its
  593. fields will be added to those of the child class. It is an error to
  594. have fields in the abstract base class with the same name as those in
  595. the child (and Django will raise an exception).
  596. An example::
  597. class CommonInfo(models.Model):
  598. name = models.CharField(max_length=100)
  599. age = models.PositiveIntegerField()
  600. class Meta:
  601. abstract = True
  602. class Student(CommonInfo):
  603. home_group = models.CharField(max_length=5)
  604. The ``Student`` model will have three fields: ``name``, ``age`` and
  605. ``home_group``. The ``CommonInfo`` model cannot be used as a normal Django
  606. model, since it is an abstract base class. It does not generate a database
  607. table or have a manager, and cannot be instantiated or saved directly.
  608. For many uses, this type of model inheritance will be exactly what you want.
  609. It provides a way to factor out common information at the Python level, whilst
  610. still only creating one database table per child model at the database level.
  611. ``Meta`` inheritance
  612. ~~~~~~~~~~~~~~~~~~~~
  613. When an abstract base class is created, Django makes any :ref:`Meta <meta-options>`
  614. inner class you declared on the base class available as an
  615. attribute. If a child class does not declared its own :ref:`Meta <meta-options>`
  616. class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to
  617. extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::
  618. class CommonInfo(models.Model):
  619. ...
  620. class Meta:
  621. abstract = True
  622. ordering = ['name']
  623. class Student(CommonInfo):
  624. ...
  625. class Meta(CommonInfo.Meta):
  626. db_table = 'student_info'
  627. Django does make one adjustment to the :ref:`Meta <meta-options>` class of an abstract base
  628. class: before installing the :ref:`Meta <meta-options>` attribute, it sets ``abstract=False``.
  629. This means that children of abstract base classes don't automatically become
  630. abstract classes themselves. Of course, you can make an abstract base class
  631. that inherits from another abstract base class. You just need to remember to
  632. explicitly set ``abstract=True`` each time.
  633. Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an
  634. abstract base class. For example, including ``db_table`` would mean that all
  635. the child classes (the ones that don't specify their own :ref:`Meta <meta-options>`) would use
  636. the same database table, which is almost certainly not what you want.
  637. .. _abstract-related-name:
  638. Be careful with ``related_name``
  639. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  640. If you are using the :attr:`~django.db.models.ForeignKey.related_name` attribute on a ``ForeignKey`` or
  641. ``ManyToManyField``, you must always specify a *unique* reverse name for the
  642. field. This would normally cause a problem in abstract base classes, since the
  643. fields on this class are included into each of the child classes, with exactly
  644. the same values for the attributes (including :attr:`~django.db.models.ForeignKey.related_name`) each time.
  645. To work around this problem, when you are using :attr:`~django.db.models.ForeignKey.related_name` in an
  646. abstract base class (only), part of the name should be the string
  647. ``'%(class)s'``. This is replaced by the lower-cased name of the child class
  648. that the field is used in. Since each class has a different name, each related
  649. name will end up being different. For example::
  650. class Base(models.Model):
  651. m2m = models.ManyToMany(OtherModel, related_name="%(class)s_related")
  652. class Meta:
  653. abstract = True
  654. class ChildA(Base):
  655. pass
  656. class ChildB(Base):
  657. pass
  658. The reverse name of the ``ChildA.m2m`` field will be ``childa_related``,
  659. whilst the reverse name of the ``ChildB.m2m`` field will be
  660. ``childb_related``. It is up to you how you use the ``'%(class)s'`` portion to
  661. construct your related name, but if you forget to use it, Django will raise
  662. errors when you validate your models (or run :djadmin:`syncdb`).
  663. If you don't specify a :attr:`~django.db.models.ForeignKey.related_name` attribute for a field in an
  664. abstract base class, the default reverse name will be the name of the
  665. child class followed by ``'_set'``, just as it normally would be if
  666. you'd declared the field directly on the child class. For example, in
  667. the above code, if the :attr:`~django.db.models.ForeignKey.related_name` attribute was omitted, the
  668. reverse name for the ``m2m`` field would be ``childa_set`` in the
  669. ``ChildA`` case and ``childb_set`` for the ``ChildB`` field.
  670. .. _multi-table-inheritance:
  671. Multi-table inheritance
  672. -----------------------
  673. The second type of model inheritance supported by Django is when each model in
  674. the hierarchy is a model all by itself. Each model corresponds to its own
  675. database table and can be queried and created indvidually. The inheritance
  676. relationship introduces links between the child model and each of its parents
  677. (via an automatically-created :class`~django.db.models.fields.OneToOneField`).
  678. For example::
  679. class Place(models.Model):
  680. name = models.CharField(max_length=50)
  681. address = models.CharField(max_length=80)
  682. class Restaurant(Place):
  683. serves_hot_dogs = models.BooleanField()
  684. serves_pizza = models.BooleanField()
  685. All of the fields of ``Place`` will also be available in ``Restaurant``,
  686. although the data will reside in a different database table. So these are both
  687. possible::
  688. >>> Place.objects.filter(name="Bob's Cafe")
  689. >>> Restaurant.objects.filter(name="Bob's Cafe")
  690. If you have a ``Place`` that is also a ``Restaurant``, you can get from the
  691. ``Place`` object to the ``Restaurant`` object by using the lower-case version
  692. of the model name::
  693. >>> p = Place.objects.filter(name="Bob's Cafe")
  694. # If Bob's Cafe is a Restaurant object, this will give the child class:
  695. >>> p.restaurant
  696. <Restaurant: ...>
  697. However, if ``p`` in the above example was *not* a ``Restaurant`` (it had been
  698. created directly as a ``Place`` object or was the parent of some other class),
  699. referring to ``p.restaurant`` would give an error.
  700. ``Meta`` and multi-table inheritance
  701. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  702. In the multi-table inheritance situation, it doesn't make sense for a child
  703. class to inherit from its parent's :ref:`Meta <meta-options>` class. All the :ref:`Meta <meta-options>` options
  704. have already been applied to the parent class and applying them again would
  705. normally only lead to contradictory behaviour (this is in contrast with the
  706. abstract base class case, where the base class doesn't exist in its own
  707. right).
  708. So a child model does not have access to its parent's :ref:`Meta <meta-options>` class. However,
  709. there are a few limited cases where the child inherits behaviour from the
  710. parent: if the child does not specify an :attr:`django.db.models.Options.ordering` attribute or a
  711. :attr:`django.db.models.Options.get_latest_by` attribute, it will inherit these from its parent.
  712. If the parent has an ordering and you don't want the child to have any natural
  713. ordering, you can explicity set it to be empty::
  714. class ChildModel(ParentModel):
  715. ...
  716. class Meta:
  717. # Remove parent's ordering effect
  718. ordering = []
  719. Inheritance and reverse relations
  720. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  721. Because multi-table inheritance uses an implicit
  722. :class:`~django.db.models.fields.OneToOneField` to link the child and
  723. the parent, it's possible to move from the parent down to the child,
  724. as in the above example. However, this uses up the name that is the
  725. default :attr:`~django.db.models.ForeignKey.related_name` value for
  726. :class:`django.db.models.fields.ForeignKey` and
  727. :class:`django.db.models.fields.ManyToManyField` relations. If you
  728. are putting those types of relations on a subclass of another model,
  729. you **must** specify the
  730. :attr:`~django.db.models.ForeignKey.related_name` attribute on each
  731. such field. If you forget, Django will raise an error when you run
  732. :djadmin:`validate` or :djadmin:`syncdb`.
  733. For example, using the above ``Place`` class again, let's create another
  734. subclass with a :class:`~django.db.models.fields.ManyToManyField`::
  735. class Supplier(Place):
  736. # Must specify related_name on all relations.
  737. customers = models.ManyToManyField(Restaurant,
  738. related_name='provider')
  739. Specifying the parent link field
  740. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  741. As mentioned, Django will automatically create a
  742. :class:`~django.db.models.fields.OneToOneField` linking your child
  743. class back any non-abstract parent models. If you want to control the
  744. name of the attribute linking back to the parent, you can create your
  745. own :class:`~django.db.models.fields.OneToOneField` and set
  746. :attr:`parent_link=True <django.db.models.fields.OneToOneField.parent_link>`
  747. to indicate that your field is the link back to the parent class.
  748. Multiple inheritance
  749. --------------------
  750. Just as with Python's subclassing, it's possible for a Django model to inherit
  751. from multiple parent models. Keep in mind that normal Python name resolution
  752. rules apply. The first base class that a particular name appears in (e.g.
  753. :ref:`Meta <meta-options>`) will be the one that is used; for example,
  754. his means that if multiple parents contain a :ref:`Meta <meta-options>` class, only
  755. the first one is going to be used, and all others will be ignored.
  756. Generally, you won't need to inherit from multiple parents. The main use-case
  757. where this is useful is for "mix-in" classes: adding a particular extra
  758. field or method to every class that inherits the mix-in. Try to keep your
  759. inheritance hierarchies as simple and straightforward as possible so that you
  760. won't have to struggle to work out where a particular piece of information is
  761. coming from.