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