Debian Codegraph @

docs/topics/db/models.txt

raw
1 ======
2 Models
3 ======
4
5 .. module:: django.db.models
6
7 A model is the single, definitive source of information about your data. It
8 contains the essential fields and behaviors of the data you're storing.
9 Generally, each 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
22 Quick example
23 =============
24
25 This example model defines a ``Person``, which has a ``first_name`` and
26 ``last_name``::
27
28 from django.db import models
29
30
31 class Person(models.Model):
32 first_name = models.CharField(max_length=30)
33 last_name = models.CharField(max_length=30)
34
35 ``first_name`` and ``last_name`` are fields_ of the model. Each field is
36 specified as a class attribute, and each attribute maps to a database column.
37
38 The above ``Person`` model would create a database table like this:
39
40 .. code-block:: sql
41
42 CREATE TABLE myapp_person (
43 "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
44 "first_name" varchar(30) NOT NULL,
45 "last_name" varchar(30) NOT NULL
46 );
47
48 Some technical notes:
49
50 * The name of the table, ``myapp_person``, is automatically derived from
51 some model metadata but can be overridden. See :ref:`table-names` for more
52 details.
53
54 * An ``id`` field is added automatically, but this behavior can be
55 overridden. See :ref:`automatic-primary-key-fields`.
56
57 * The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL
58 syntax, but it's worth noting Django uses SQL tailored to the database
59 backend specified in your :doc:`settings file </topics/settings>`.
60
61 Using models
62 ============
63
64 Once you have defined your models, you need to tell Django you're going to *use*
65 those models. Do this by editing your settings file and changing the
66 :setting:`INSTALLED_APPS` setting to add the name of the module that contains
67 your ``models.py``.
68
69 For example, if the models for your application live in the module
70 ``myapp.models`` (the package structure that is created for an
71 application by the :djadmin:`manage.py startapp <startapp>` script),
72 :setting:`INSTALLED_APPS` should read, in part::
73
74 INSTALLED_APPS = [
75 # ...
76 "myapp",
77 # ...
78 ]
79
80 When you add new apps to :setting:`INSTALLED_APPS`, be sure to run
81 :djadmin:`manage.py migrate <migrate>`, optionally making migrations
82 for them first with :djadmin:`manage.py makemigrations <makemigrations>`.
83
84 Fields
85 ======
86
87 The most important part of a model -- and the only required part of a model --
88 is the list of database fields it defines. Fields are specified by class
89 attributes. Be careful not to choose field names that conflict with the
90 :doc:`models API </ref/models/instances>` like ``clean``, ``save``, or
91 ``delete``.
92
93 Example::
94
95 from django.db import models
96
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
104 class Album(models.Model):
105 artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
106 name = models.CharField(max_length=100)
107 release_date = models.DateField()
108 num_stars = models.IntegerField()
109
110 Field types
111 -----------
112
113 Each field in your model should be an instance of the appropriate
114 :class:`~django.db.models.Field` class. Django uses the field class types to
115 determine a few things:
116
117 * The column type, which tells the database what kind of data to store (e.g.
118 ``INTEGER``, ``VARCHAR``, ``TEXT``).
119
120 * The default HTML :doc:`widget </ref/forms/widgets>` to use when rendering a form
121 field (e.g. ``<input type="text">``, ``<select>``).
122
123 * The minimal validation requirements, used in Django's admin and in
124 automatically-generated forms.
125
126 Django ships with dozens of built-in field types; you can find the complete list
127 in the :ref:`model field reference <model-field-types>`. You can easily write
128 your own fields if Django's built-in ones don't do the trick; see
129 :doc:`/howto/custom-model-fields`.
130
131 Field options
132 -------------
133
134 Each field takes a certain set of field-specific arguments (documented in the
135 :ref:`model field reference <model-field-types>`). For example,
136 :class:`~django.db.models.CharField` (and its subclasses) require a
137 :attr:`~django.db.models.CharField.max_length` argument which specifies the size
138 of the ``VARCHAR`` database field used to store the data.
139
140 There's also a set of common arguments available to all field types. All are
141 optional. They're fully explained in the :ref:`reference
142 <common-model-field-options>`, but here's a quick summary of the most often-used
143 ones:
144
145 :attr:`~Field.null`
146 If ``True``, Django will store empty values as ``NULL`` in the database.
147 Default is ``False``.
148
149 :attr:`~Field.blank`
150 If ``True``, the field is allowed to be blank. Default is ``False``.
151
152 Note that this is different than :attr:`~Field.null`.
153 :attr:`~Field.null` is purely database-related, whereas
154 :attr:`~Field.blank` is validation-related. If a field has
155 :attr:`blank=True <Field.blank>`, form validation will
156 allow entry of an empty value. If a field has :attr:`blank=False
157 <Field.blank>`, the field will be required.
158
159 :attr:`~Field.choices`
160 A :term:`sequence` of 2-value tuples, a :term:`mapping`, an
161 :ref:`enumeration type <field-choices-enum-types>`, or a callable (that
162 expects no arguments and returns any of the previous formats), to use as
163 choices for this field. If this is given, the default form widget will be a
164 select box instead of the standard text field and will limit choices to the
165 choices given.
166
167 A choices list looks like this::
168
169 YEAR_IN_SCHOOL_CHOICES = [
170 ("FR", "Freshman"),
171 ("SO", "Sophomore"),
172 ("JR", "Junior"),
173 ("SR", "Senior"),
174 ("GR", "Graduate"),
175 ]
176
177 .. note::
178 A new migration is created each time the order of ``choices`` changes.
179
180 The first element in each tuple is the value that will be stored in the
181 database. The second element is displayed by the field's form widget.
182
183 Given a model instance, the display value for a field with ``choices`` can
184 be accessed using the :meth:`~django.db.models.Model.get_FOO_display`
185 method. For example::
186
187 from django.db import models
188
189
190 class Person(models.Model):
191 SHIRT_SIZES = {
192 "S": "Small",
193 "M": "Medium",
194 "L": "Large",
195 }
196 name = models.CharField(max_length=60)
197 shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
198
199 .. code-block:: pycon
200
201 >>> p = Person(name="Fred Flintstone", shirt_size="L")
202 >>> p.save()
203 >>> p.shirt_size
204 'L'
205 >>> p.get_shirt_size_display()
206 'Large'
207
208 You can also use enumeration classes to define ``choices`` in a concise
209 way::
210
211 from django.db import models
212
213
214 class Runner(models.Model):
215 MedalType = models.TextChoices("MedalType", "GOLD SILVER BRONZE")
216 name = models.CharField(max_length=60)
217 medal = models.CharField(blank=True, choices=MedalType, max_length=10)
218
219 Further examples are available in the :ref:`model field reference
220 <field-choices>`.
221
222 :attr:`~Field.default`
223 The default value for the field. This can be a value or a callable
224 object. If callable it will be called every time a new object is
225 created.
226
227 :attr:`~Field.db_default`
228 The database-computed default value for the field. This can be a literal
229 value or a database function.
230
231 If both ``db_default`` and :attr:`Field.default` are set, ``default`` will
232 take precedence when creating instances in Python code. ``db_default`` will
233 still be set at the database level and will be used when inserting rows
234 outside of the ORM or when adding a new field in a migration.
235
236 :attr:`~Field.help_text`
237 Extra "help" text to be displayed with the form widget. It's useful for
238 documentation even if your field isn't used on a form.
239
240 :attr:`~Field.primary_key`
241 If ``True``, this field is the primary key for the model.
242
243 If you don't specify :attr:`primary_key=True <Field.primary_key>` for
244 any fields in your model, Django will automatically add a field to hold
245 the primary key, so you don't need to set
246 :attr:`primary_key=True <Field.primary_key>` on any of your fields
247 unless you want to override the default primary-key behavior. For more,
248 see :ref:`automatic-primary-key-fields`.
249
250 The primary key field is read-only. If you change the value of the primary
251 key on an existing object and then save it, a new object will be created
252 alongside the old one. For example::
253
254 from django.db import models
255
256
257 class Fruit(models.Model):
258 name = models.CharField(max_length=100, primary_key=True)
259
260 .. code-block:: pycon
261
262 >>> fruit = Fruit.objects.create(name="Apple")
263 >>> fruit.name = "Pear"
264 >>> fruit.save()
265 >>> Fruit.objects.values_list("name", flat=True)
266 <QuerySet ['Apple', 'Pear']>
267
268 :attr:`~Field.unique`
269 If ``True``, this field must be unique throughout the table.
270
271 Again, these are just short descriptions of the most common field options. Full
272 details can be found in the :ref:`common model field option reference
273 <common-model-field-options>`.
274
275 .. _automatic-primary-key-fields:
276
277 Automatic primary key fields
278 ----------------------------
279
280 By default, Django gives each model an auto-incrementing primary key with the
281 type specified per app in :attr:`AppConfig.default_auto_field
282 <django.apps.AppConfig.default_auto_field>` or globally in the
283 :setting:`DEFAULT_AUTO_FIELD` setting. For example::
284
285 id = models.BigAutoField(primary_key=True)
286
287 If you'd like to specify a custom primary key, specify
288 :attr:`primary_key=True <Field.primary_key>` on one of your fields. If Django
289 sees you've explicitly set :attr:`Field.primary_key`, it won't add the automatic
290 ``id`` column.
291
292 Each model requires exactly one field to have :attr:`primary_key=True
293 <Field.primary_key>` (either explicitly declared or automatically added).
294
295 .. _verbose-field-names:
296
297 Verbose field names
298 -------------------
299
300 Each field type, except for :class:`~django.db.models.ForeignKey`,
301 :class:`~django.db.models.ManyToManyField` and
302 :class:`~django.db.models.OneToOneField`, takes an optional first positional
303 argument -- a verbose name. If the verbose name isn't given, Django will
304 automatically create it using the field's attribute name, converting underscores
305 to spaces.
306
307 In this example, the verbose name is ``"person's first name"``::
308
309 first_name = models.CharField("person's first name", max_length=30)
310
311 In this example, the verbose name is ``"first name"``::
312
313 first_name = models.CharField(max_length=30)
314
315 :class:`~django.db.models.ForeignKey`,
316 :class:`~django.db.models.ManyToManyField` and
317 :class:`~django.db.models.OneToOneField` require the first argument to be a
318 model class, so use the :attr:`~Field.verbose_name` keyword argument::
319
320 poll = models.ForeignKey(
321 Poll,
322 on_delete=models.CASCADE,
323 verbose_name="the related poll",
324 )
325 sites = models.ManyToManyField(Site, verbose_name="list of sites")
326 place = models.OneToOneField(
327 Place,
328 on_delete=models.CASCADE,
329 verbose_name="related place",
330 )
331
332 The convention is not to capitalize the first letter of the
333 :attr:`~Field.verbose_name`. Django will automatically capitalize the first
334 letter where it needs to.
335
336 Relationships
337 -------------
338
339 Clearly, the power of relational databases lies in relating tables to each
340 other. Django offers ways to define the three most common types of database
341 relationships: many-to-one, many-to-many and one-to-one.
342
343 Many-to-one relationships
344 ~~~~~~~~~~~~~~~~~~~~~~~~~
345
346 To define a many-to-one relationship, use :class:`django.db.models.ForeignKey`.
347 You use it just like any other :class:`~django.db.models.Field` type: by
348 including it as a class attribute of your model.
349
350 :class:`~django.db.models.ForeignKey` requires a positional argument: the class
351 to which the model is related.
352
353 For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
354 ``Manufacturer`` makes multiple cars but each ``Car`` only has one
355 ``Manufacturer`` -- use the following definitions::
356
357 from django.db import models
358
359
360 class Manufacturer(models.Model):
361 # ...
362 pass
363
364
365 class Car(models.Model):
366 manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
367 # ...
368
369 You can also create :ref:`recursive relationships <recursive-relationships>` (an
370 object with a many-to-one relationship to itself) and :ref:`relationships to
371 models not yet defined <lazy-relationships>`; see :ref:`the model field
372 reference <ref-foreignkey>` for details.
373
374 It's suggested, but not required, that the name of a
375 :class:`~django.db.models.ForeignKey` field (``manufacturer`` in the example
376 above) be the name of the model, lowercase. You can call the field whatever you
377 want. For example::
378
379 class Car(models.Model):
380 company_that_makes_it = models.ForeignKey(
381 Manufacturer,
382 on_delete=models.CASCADE,
383 )
384 # ...
385
386 .. seealso::
387
388 :class:`~django.db.models.ForeignKey` fields accept a number of extra
389 arguments which are explained in :ref:`the model field reference
390 <foreign-key-arguments>`. These options help define how the relationship
391 should work; all are optional.
392
393 For details on accessing backwards-related objects, see the
394 :ref:`Following relationships backward example <backwards-related-objects>`.
395
396 For sample code, see the :doc:`Many-to-one relationship model example
397 </topics/db/examples/many_to_one>`.
398
399
400 Many-to-many relationships
401 ~~~~~~~~~~~~~~~~~~~~~~~~~~
402
403 To define a many-to-many relationship, use
404 :class:`~django.db.models.ManyToManyField`. You use it just like any other
405 :class:`~django.db.models.Field` type: by including it as a class attribute of
406 your model.
407
408 :class:`~django.db.models.ManyToManyField` requires a positional argument: the
409 class to which the model is related.
410
411 For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
412 ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings
413 -- here's how you'd represent that::
414
415 from django.db import models
416
417
418 class Topping(models.Model):
419 # ...
420 pass
421
422
423 class Pizza(models.Model):
424 # ...
425 toppings = models.ManyToManyField(Topping)
426
427 As with :class:`~django.db.models.ForeignKey`, you can also create
428 :ref:`recursive relationships <recursive-relationships>` (an object with a
429 many-to-many relationship to itself) and :ref:`relationships to models not yet
430 defined <lazy-relationships>`.
431
432 It's suggested, but not required, that the name of a
433 :class:`~django.db.models.ManyToManyField` (``toppings`` in the example above)
434 be a plural describing the set of related model objects.
435
436 It doesn't matter which model has the
437 :class:`~django.db.models.ManyToManyField`, but you should only put it in one
438 of the models -- not both.
439
440 Generally, :class:`~django.db.models.ManyToManyField` instances should go in
441 the object that's going to be edited on a form. In the above example,
442 ``toppings`` is in ``Pizza`` (rather than ``Topping`` having a ``pizzas``
443 :class:`~django.db.models.ManyToManyField` ) because it's more natural to think
444 about a pizza having toppings than a topping being on multiple pizzas. The way
445 it's set up above, the ``Pizza`` form would let users select the toppings.
446
447 .. seealso::
448
449 See the :doc:`Many-to-many relationship model example
450 </topics/db/examples/many_to_many>` for a full example.
451
452 :class:`~django.db.models.ManyToManyField` fields also accept a number of
453 extra arguments which are explained in :ref:`the model field reference
454 <manytomany-arguments>`. These options help define how the relationship
455 should work; all are optional.
456
457 .. _intermediary-manytomany:
458
459 Extra fields on many-to-many relationships
460 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
461
462 When you're only dealing with many-to-many relationships such as mixing and
463 matching pizzas and toppings, a standard
464 :class:`~django.db.models.ManyToManyField` is all you need. However, sometimes
465 you may need to associate data with the relationship between two models.
466
467 For example, consider the case of an application tracking the musical groups
468 which musicians belong to. There is a many-to-many relationship between a person
469 and the groups of which they are a member, so you could use a
470 :class:`~django.db.models.ManyToManyField` to represent this relationship.
471 However, there is a lot of detail about the membership that you might want to
472 collect, such as the date at which the person joined the group.
473
474 For these situations, Django allows you to specify the model that will be used
475 to govern the many-to-many relationship. You can then put extra fields on the
476 intermediate model. The intermediate model is associated with the
477 :class:`~django.db.models.ManyToManyField` using the
478 :attr:`through <ManyToManyField.through>` argument to point to the model
479 that will act as an intermediary. For our musician example, the code would look
480 something like this::
481
482 from django.db import models
483
484
485 class Person(models.Model):
486 name = models.CharField(max_length=128)
487
488 def __str__(self):
489 return self.name
490
491
492 class Group(models.Model):
493 name = models.CharField(max_length=128)
494 members = models.ManyToManyField(Person, through="Membership")
495
496 def __str__(self):
497 return self.name
498
499
500 class Membership(models.Model):
501 person = models.ForeignKey(Person, on_delete=models.CASCADE)
502 group = models.ForeignKey(Group, on_delete=models.CASCADE)
503 date_joined = models.DateField()
504 invite_reason = models.CharField(max_length=64)
505
506 class Meta:
507 constraints = [
508 models.UniqueConstraint(
509 fields=["person", "group"], name="unique_person_group"
510 )
511 ]
512
513 When you set up the intermediary model, you explicitly specify foreign
514 keys to the models that are involved in the many-to-many relationship. This
515 explicit declaration defines how the two models are related.
516
517 If you don't want multiple associations between the same instances, add a
518 :class:`~django.db.models.UniqueConstraint` including the ``from`` and ``to``
519 fields. Django's automatically generated many-to-many tables include such a
520 constraint.
521
522 There are a few restrictions on the intermediate model:
523
524 * Your intermediate model must contain one - and *only* one - foreign key
525 to the source model (this would be ``Group`` in our example), or you must
526 explicitly specify the foreign keys Django should use for the relationship
527 using :attr:`ManyToManyField.through_fields <ManyToManyField.through_fields>`.
528 If you have more than one foreign key and ``through_fields`` is not
529 specified, a validation error will be raised. A similar restriction applies
530 to the foreign key to the target model (this would be ``Person`` in our
531 example).
532
533 * For a model which has a many-to-many relationship to itself through an
534 intermediary model, two foreign keys to the same model are permitted, but
535 they will be treated as the two (different) sides of the many-to-many
536 relationship. If :attr:`~.ManyToManyField.through_fields` is not specified,
537 the first foreign key will be taken to represent the source side of the
538 ``ManyToManyField``, while the second will be taken to represent the target
539 side. If there are *more* than two foreign keys though, you must specify
540 :attr:`~.ManyToManyField.through_fields` to explicitly indicate which foreign
541 keys to use, otherwise a validation error will be raised.
542
543 Now that you have set up your :class:`~django.db.models.ManyToManyField` to use
544 your intermediary model (``Membership``, in this case), you're ready to start
545 creating some many-to-many relationships. You do this by creating instances of
546 the intermediate model:
547
548 .. code-block:: pycon
549
550 >>> ringo = Person.objects.create(name="Ringo Starr")
551 >>> paul = Person.objects.create(name="Paul McCartney")
552 >>> beatles = Group.objects.create(name="The Beatles")
553 >>> m1 = Membership(
554 ... person=ringo,
555 ... group=beatles,
556 ... date_joined=date(1962, 8, 16),
557 ... invite_reason="Needed a new drummer.",
558 ... )
559 >>> m1.save()
560 >>> beatles.members.all()
561 <QuerySet [<Person: Ringo Starr>]>
562 >>> ringo.group_set.all()
563 <QuerySet [<Group: The Beatles>]>
564 >>> m2 = Membership.objects.create(
565 ... person=paul,
566 ... group=beatles,
567 ... date_joined=date(1960, 8, 1),
568 ... invite_reason="Wanted to form a band.",
569 ... )
570 >>> beatles.members.all()
571 <QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>]>
572
573 You can also use :meth:`~django.db.models.fields.related.RelatedManager.add`,
574 :meth:`~django.db.models.fields.related.RelatedManager.create`, or
575 :meth:`~django.db.models.fields.related.RelatedManager.set` to create
576 relationships, as long as you specify ``through_defaults`` for any required
577 fields:
578
579 .. code-block:: pycon
580
581 >>> beatles.members.add(john, through_defaults={"date_joined": date(1960, 8, 1)})
582 >>> beatles.members.create(
583 ... name="George Harrison", through_defaults={"date_joined": date(1960, 8, 1)}
584 ... )
585 >>> beatles.members.set(
586 ... [john, paul, ringo, george], through_defaults={"date_joined": date(1960, 8, 1)}
587 ... )
588
589 You may prefer to create instances of the intermediate model directly.
590
591 If the custom through table defined by the intermediate model does not enforce
592 uniqueness on the ``(model1, model2)`` pair, allowing multiple values, the
593 :meth:`~django.db.models.fields.related.RelatedManager.remove` call will
594 remove all intermediate model instances:
595
596 .. code-block:: pycon
597
598 >>> Membership.objects.create(
599 ... person=ringo,
600 ... group=beatles,
601 ... date_joined=date(1968, 9, 4),
602 ... invite_reason="You've been gone for a month and we miss you.",
603 ... )
604 >>> beatles.members.all()
605 <QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>, <Person: Ringo Starr>]>
606 >>> # This deletes both of the intermediate model instances for Ringo Starr
607 >>> beatles.members.remove(ringo)
608 >>> beatles.members.all()
609 <QuerySet [<Person: Paul McCartney>]>
610
611 The :meth:`~django.db.models.fields.related.RelatedManager.clear`
612 method can be used to remove all many-to-many relationships for an instance:
613
614 .. code-block:: pycon
615
616 >>> # Beatles have broken up
617 >>> beatles.members.clear()
618 >>> # Note that this deletes the intermediate model instances
619 >>> Membership.objects.all()
620 <QuerySet []>
621
622 Once you have established the many-to-many relationships, you can issue
623 queries. Just as with normal many-to-many relationships, you can query using
624 the attributes of the many-to-many-related model:
625
626 .. code-block:: pycon
627
628 # Find all the groups with a member whose name starts with 'Paul'
629 >>> Group.objects.filter(members__name__startswith="Paul")
630 <QuerySet [<Group: The Beatles>]>
631
632 As you are using an intermediate model, you can also query on its attributes:
633
634 .. code-block:: pycon
635
636 # Find all the members of the Beatles that joined after 1 Jan 1961
637 >>> Person.objects.filter(
638 ... group__name="The Beatles", membership__date_joined__gt=date(1961, 1, 1)
639 ... )
640 <QuerySet [<Person: Ringo Starr]>
641
642 If you need to access a membership's information you may do so by directly
643 querying the ``Membership`` model:
644
645 .. code-block:: pycon
646
647 >>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
648 >>> ringos_membership.date_joined
649 datetime.date(1962, 8, 16)
650 >>> ringos_membership.invite_reason
651 'Needed a new drummer.'
652
653 Another way to access the same information is by querying the
654 :ref:`many-to-many reverse relationship<m2m-reverse-relationships>` from a
655 ``Person`` object:
656
657 .. code-block:: pycon
658
659 >>> ringos_membership = ringo.membership_set.get(group=beatles)
660 >>> ringos_membership.date_joined
661 datetime.date(1962, 8, 16)
662 >>> ringos_membership.invite_reason
663 'Needed a new drummer.'
664
665 One-to-one relationships
666 ~~~~~~~~~~~~~~~~~~~~~~~~
667
668 To define a one-to-one relationship, use
669 :class:`~django.db.models.OneToOneField`. You use it just like any other
670 ``Field`` type: by including it as a class attribute of your model.
671
672 This is most useful on the primary key of an object when that object "extends"
673 another object in some way.
674
675 :class:`~django.db.models.OneToOneField` requires a positional argument: the
676 class to which the model is related.
677
678 For example, if you were building a database of "places", you would
679 build pretty standard stuff such as address, phone number, etc. in the
680 database. Then, if you wanted to build a database of restaurants on
681 top of the places, instead of repeating yourself and replicating those
682 fields in the ``Restaurant`` model, you could make ``Restaurant`` have
683 a :class:`~django.db.models.OneToOneField` to ``Place`` (because a
684 restaurant "is a" place; in fact, to handle this you'd typically use
685 :ref:`inheritance <model-inheritance>`, which involves an implicit
686 one-to-one relation).
687
688 As with :class:`~django.db.models.ForeignKey`, a :ref:`recursive relationship
689 <recursive-relationships>` can be defined and :ref:`references to as-yet
690 undefined models <lazy-relationships>` can be made.
691
692 .. seealso::
693
694 See the :doc:`One-to-one relationship model example
695 </topics/db/examples/one_to_one>` for a full example.
696
697 :class:`~django.db.models.OneToOneField` fields also accept an optional
698 :attr:`~django.db.models.OneToOneField.parent_link` argument.
699
700 :class:`~django.db.models.OneToOneField` classes used to automatically become
701 the primary key on a model. This is no longer true (although you can manually
702 pass in the :attr:`~django.db.models.Field.primary_key` argument if you like).
703 Thus, it's now possible to have multiple fields of type
704 :class:`~django.db.models.OneToOneField` on a single model.
705
706 Models across files
707 -------------------
708
709 It's perfectly OK to relate a model to one from another app. To do this, import
710 the related model at the top of the file where your model is defined. Then,
711 refer to the other model class wherever needed. For example::
712
713 from django.db import models
714 from geography.models import ZipCode
715
716
717 class Restaurant(models.Model):
718 # ...
719 zip_code = models.ForeignKey(
720 ZipCode,
721 on_delete=models.SET_NULL,
722 blank=True,
723 null=True,
724 )
725
726 Alternatively, you can use a lazy reference to the related model, specified as
727 a string in the format ``"app_label.ModelName"``. This does not require the
728 related model to be imported. For example::
729
730 from django.db import models
731
732
733 class Restaurant(models.Model):
734 # ...
735 zip_code = models.ForeignKey(
736 "geography.ZipCode",
737 on_delete=models.SET_NULL,
738 blank=True,
739 null=True,
740 )
741
742 See :ref:`lazy relationships <lazy-relationships>` for more details.
743
744 Field name restrictions
745 -----------------------
746
747 Django places some restrictions on model field names:
748
749 #. A field name cannot be a Python reserved word, because that would result
750 in a Python syntax error. For example:
751
752 .. code-block:: text
753
754 class Example(models.Model):
755 pass = models.IntegerField() # 'pass' is a reserved word!
756
757 #. A field name cannot contain more than one underscore in a row, due to
758 the way Django's query lookup syntax works. For example::
759
760 class Example(models.Model):
761 foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
762
763 #. A field name cannot end with an underscore, for similar reasons.
764
765 #. A field name cannot be ``check``, as this would override the check
766 framework's ``Model.check()`` method.
767
768 These limitations can be worked around, though, because your field name doesn't
769 necessarily have to match your database column name. See the
770 :attr:`~Field.db_column` option.
771
772 SQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as
773 model field names, because Django escapes all database table names and column
774 names in every underlying SQL query. It uses the quoting syntax of your
775 particular database engine.
776
777 Custom field types
778 ------------------
779
780 If one of the existing model fields cannot be used to fit your purposes, or if
781 you wish to take advantage of some less common database column types, you can
782 create your own field class. Full coverage of creating your own fields is
783 provided in :doc:`/howto/custom-model-fields`.
784
785 .. _meta-options:
786
787 ``Meta`` options
788 ================
789
790 Give your model metadata by using an inner ``class Meta``, like so::
791
792 from django.db import models
793
794
795 class Ox(models.Model):
796 horn_length = models.IntegerField()
797
798 class Meta:
799 ordering = ["horn_length"]
800 verbose_name_plural = "oxen"
801
802 Model metadata is "anything that's not a field", such as ordering options
803 (:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), or
804 human-readable singular and plural names (:attr:`~Options.verbose_name` and
805 :attr:`~Options.verbose_name_plural`). None are required, and adding ``class
806 Meta`` to a model is completely optional.
807
808 A complete list of all possible ``Meta`` options can be found in the :doc:`model
809 option reference </ref/models/options>`.
810
811 .. _model-attributes:
812
813 Model attributes
814 ================
815
816 ``objects``
817 The most important attribute of a model is the
818 :class:`~django.db.models.Manager`. It's the interface through which
819 database query operations are provided to Django models and is used to
820 :ref:`retrieve the instances <retrieving-objects>` from the database. If no
821 custom ``Manager`` is defined, the default name is
822 :attr:`~django.db.models.Model.objects`. Managers are only accessible via
823 model classes, not the model instances.
824
825 .. _model-methods:
826
827 Model methods
828 =============
829
830 Define custom methods on a model to add custom "row-level" functionality to your
831 objects. Whereas :class:`~django.db.models.Manager` methods are intended to do
832 "table-wide" things, model methods should act on a particular model instance.
833
834 This is a valuable technique for keeping business logic in one place -- the
835 model.
836
837 For example, this model has a few custom methods::
838
839 from django.db import models
840
841
842 class Person(models.Model):
843 first_name = models.CharField(max_length=50)
844 last_name = models.CharField(max_length=50)
845 birth_date = models.DateField()
846
847 def baby_boomer_status(self):
848 "Returns the person's baby-boomer status."
849 import datetime
850
851 if self.birth_date < datetime.date(1945, 8, 1):
852 return "Pre-boomer"
853 elif self.birth_date < datetime.date(1965, 1, 1):
854 return "Baby boomer"
855 else:
856 return "Post-boomer"
857
858 @property
859 def full_name(self):
860 "Returns the person's full name."
861 return f"{self.first_name} {self.last_name}"
862
863 The last method in this example is a :term:`property`.
864
865 The :doc:`model instance reference </ref/models/instances>` has a complete list
866 of :ref:`methods automatically given to each model <model-instance-methods>`.
867 You can override most of these -- see `overriding predefined model methods`_,
868 below -- but there are a couple that you'll almost always want to define:
869
870 :meth:`~Model.__str__`
871 A Python "magic method" that returns a string representation of any
872 object. This is what Python and Django will use whenever a model
873 instance needs to be coerced and displayed as a plain string. Most
874 notably, this happens when you display an object in an interactive
875 console or in the admin.
876
877 You'll always want to define this method; the default isn't very helpful
878 at all.
879
880 :meth:`~Model.get_absolute_url`
881 This tells Django how to calculate the URL for an object. Django uses
882 this in its admin interface, and any time it needs to figure out a URL
883 for an object.
884
885 Any object that has a URL that uniquely identifies it should define this
886 method.
887
888 .. _overriding-model-methods:
889
890 Overriding predefined model methods
891 -----------------------------------
892
893 There's another set of :ref:`model methods <model-instance-methods>` that
894 encapsulate a bunch of database behavior that you'll want to customize. In
895 particular you'll often want to change the way :meth:`~Model.save` and
896 :meth:`~Model.delete` work.
897
898 You're free to override these methods (and any other model method) to alter
899 behavior.
900
901 A classic use-case for overriding the built-in methods is if you want something
902 to happen whenever you save an object. For example (see
903 :meth:`~Model.save` for documentation of the parameters it accepts)::
904
905 from django.db import models
906
907
908 class Blog(models.Model):
909 name = models.CharField(max_length=100)
910 tagline = models.TextField()
911
912 def save(self, **kwargs):
913 do_something()
914 super().save(**kwargs) # Call the "real" save() method.
915 do_something_else()
916
917 You can also prevent saving::
918
919 from django.db import models
920
921
922 class Blog(models.Model):
923 name = models.CharField(max_length=100)
924 tagline = models.TextField()
925
926 def save(self, **kwargs):
927 if self.name == "Yoko Ono's blog":
928 return # Yoko shall never have her own blog!
929 else:
930 super().save(**kwargs) # Call the "real" save() method.
931
932 It's important to remember to call the superclass method -- that's
933 that ``super().save(**kwargs)`` business -- to ensure that the object still
934 gets saved into the database. If you forget to call the superclass method, the
935 default behavior won't happen and the database won't get touched.
936
937 It's also important that you pass through the arguments that can be
938 passed to the model method -- that's what the ``**kwargs`` bit does. Django
939 will, from time to time, extend the capabilities of built-in model methods,
940 adding new keyword arguments. If you use ``**kwargs`` in your method
941 definitions, you are guaranteed that your code will automatically support those
942 arguments when they are added.
943
944 If you wish to update a field value in the :meth:`~Model.save` method, you may
945 also want to have this field added to the ``update_fields`` keyword argument.
946 This will ensure the field is saved when ``update_fields`` is specified. For
947 example::
948
949 from django.db import models
950 from django.utils.text import slugify
951
952
953 class Blog(models.Model):
954 name = models.CharField(max_length=100)
955 slug = models.TextField()
956
957 def save(self, **kwargs):
958 self.slug = slugify(self.name)
959 if (
960 update_fields := kwargs.get("update_fields")
961 ) is not None and "name" in update_fields:
962 kwargs["update_fields"] = {"slug"}.union(update_fields)
963 super().save(**kwargs)
964
965 See :ref:`ref-models-update-fields` for more details.
966
967 .. admonition:: Overridden model methods are not called on bulk operations
968
969 Note that the :meth:`~Model.delete()` method for an object is not
970 necessarily called when :ref:`deleting objects in bulk using a
971 QuerySet <topics-db-queries-delete>` or as a result of a :attr:`cascading
972 delete <django.db.models.ForeignKey.on_delete>`. To ensure customized
973 delete logic gets executed, you can use
974 :data:`~django.db.models.signals.pre_delete` and/or
975 :data:`~django.db.models.signals.post_delete` signals.
976
977 Unfortunately, there isn't a workaround when
978 :meth:`creating<django.db.models.query.QuerySet.bulk_create>` or
979 :meth:`updating<django.db.models.query.QuerySet.update>` objects in bulk,
980 since none of :meth:`~Model.save()`,
981 :data:`~django.db.models.signals.pre_save`, and
982 :data:`~django.db.models.signals.post_save` are called.
983
984 Executing custom SQL
985 --------------------
986
987 Another common pattern is writing custom SQL statements in model methods and
988 module-level methods. For more details on using raw SQL, see the documentation
989 on :doc:`using raw SQL</topics/db/sql>`.
990
991 .. _model-inheritance:
992
993 Model inheritance
994 =================
995
996 Model inheritance in Django works almost identically to the way normal
997 class inheritance works in Python, but the basics at the beginning of the page
998 should still be followed. That means the base class should subclass
999 :class:`django.db.models.Model`.
1000
1001 The only decision you have to make is whether you want the parent models to be
1002 models in their own right (with their own database tables), or if the parents
1003 are just holders of common information that will only be visible through the
1004 child models.
1005
1006 There are three styles of inheritance that are possible in Django.
1007
1008 1. Often, you will just want to use the parent class to hold information that
1009 you don't want to have to type out for each child model. This class isn't
1010 going to ever be used in isolation, so :ref:`abstract-base-classes` are
1011 what you're after.
1012 2. If you're subclassing an existing model (perhaps something from another
1013 application entirely) and want each model to have its own database table,
1014 :ref:`multi-table-inheritance` is the way to go.
1015 3. Finally, if you only want to modify the Python-level behavior of a model,
1016 without changing the models fields in any way, you can use
1017 :ref:`proxy-models`.
1018
1019 .. _abstract-base-classes:
1020
1021 Abstract base classes
1022 ---------------------
1023
1024 Abstract base classes are useful when you want to put some common
1025 information into a number of other models. You write your base class
1026 and put ``abstract=True`` in the :ref:`Meta <meta-options>`
1027 class. This model will then not be used to create any database
1028 table. Instead, when it is used as a base class for other models, its
1029 fields will be added to those of the child class.
1030
1031 An example::
1032
1033 from django.db import models
1034
1035
1036 class CommonInfo(models.Model):
1037 name = models.CharField(max_length=100)
1038 age = models.PositiveIntegerField()
1039
1040 class Meta:
1041 abstract = True
1042
1043
1044 class Student(CommonInfo):
1045 home_group = models.CharField(max_length=5)
1046
1047 The ``Student`` model will have three fields: ``name``, ``age`` and
1048 ``home_group``. The ``CommonInfo`` model cannot be used as a normal Django
1049 model, since it is an abstract base class. It does not generate a database
1050 table or have a manager, and cannot be instantiated or saved directly.
1051
1052 Fields inherited from abstract base classes can be overridden with another
1053 field or value, or be removed with ``None``.
1054
1055 For many uses, this type of model inheritance will be exactly what you want.
1056 It provides a way to factor out common information at the Python level, while
1057 still only creating one database table per child model at the database level.
1058
1059 ``Meta`` inheritance
1060 ~~~~~~~~~~~~~~~~~~~~
1061
1062 When an abstract base class is created, Django makes any :ref:`Meta <meta-options>`
1063 inner class you declared in the base class available as an
1064 attribute. If a child class does not declare its own :ref:`Meta <meta-options>`
1065 class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to
1066 extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::
1067
1068 from django.db import models
1069
1070
1071 class CommonInfo(models.Model):
1072 # ...
1073 class Meta:
1074 abstract = True
1075 ordering = ["name"]
1076
1077
1078 class Student(CommonInfo):
1079 # ...
1080 class Meta(CommonInfo.Meta):
1081 db_table = "student_info"
1082
1083 Django does make one adjustment to the :ref:`Meta <meta-options>` class of an
1084 abstract base class: before installing the :ref:`Meta <meta-options>`
1085 attribute, it sets ``abstract=False``. This means that children of abstract
1086 base classes don't automatically become abstract classes themselves. To make
1087 an abstract base class that inherits from another abstract base class, you need
1088 to explicitly set ``abstract=True`` on the child.
1089
1090 Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an
1091 abstract base class. For example, including ``db_table`` would mean that all
1092 the child classes (the ones that don't specify their own :ref:`Meta <meta-options>`) would use
1093 the same database table, which is almost certainly not what you want.
1094
1095 Due to the way Python inheritance works, if a child class inherits from
1096 multiple abstract base classes, only the :ref:`Meta <meta-options>` options
1097 from the first listed class will be inherited by default. To inherit :ref:`Meta
1098 <meta-options>` options from multiple abstract base classes, you must
1099 explicitly declare the :ref:`Meta <meta-options>` inheritance. For example::
1100
1101 from django.db import models
1102
1103
1104 class CommonInfo(models.Model):
1105 name = models.CharField(max_length=100)
1106 age = models.PositiveIntegerField()
1107
1108 class Meta:
1109 abstract = True
1110 ordering = ["name"]
1111
1112
1113 class Unmanaged(models.Model):
1114 class Meta:
1115 abstract = True
1116 managed = False
1117
1118
1119 class Student(CommonInfo, Unmanaged):
1120 home_group = models.CharField(max_length=5)
1121
1122 class Meta(CommonInfo.Meta, Unmanaged.Meta):
1123 pass
1124
1125 .. _abstract-related-name:
1126
1127 Be careful with ``related_name`` and ``related_query_name``
1128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1129
1130 If you are using :attr:`~django.db.models.ForeignKey.related_name` or
1131 :attr:`~django.db.models.ForeignKey.related_query_name` on a ``ForeignKey`` or
1132 ``ManyToManyField``, you must always specify a *unique* reverse name and query
1133 name for the field. This would normally cause a problem in abstract base
1134 classes, since the fields on this class are included into each of the child
1135 classes, with exactly the same values for the attributes (including
1136 :attr:`~django.db.models.ForeignKey.related_name` and
1137 :attr:`~django.db.models.ForeignKey.related_query_name`) each time.
1138
1139 To work around this problem, when you are using
1140 :attr:`~django.db.models.ForeignKey.related_name` or
1141 :attr:`~django.db.models.ForeignKey.related_query_name` in an abstract base
1142 class (only), part of the value should contain ``'%(app_label)s'`` and
1143 ``'%(class)s'``.
1144
1145 - ``'%(class)s'`` is replaced by the lowercased name of the child class that
1146 the field is used in.
1147 - ``'%(app_label)s'`` is replaced by the lowercased name of the app the child
1148 class is contained within. Each installed application name must be unique and
1149 the model class names within each app must also be unique, therefore the
1150 resulting name will end up being different.
1151
1152 For example, given an app ``common/models.py``::
1153
1154 from django.db import models
1155
1156
1157 class Base(models.Model):
1158 m2m = models.ManyToManyField(
1159 OtherModel,
1160 related_name="%(app_label)s_%(class)s_related",
1161 related_query_name="%(app_label)s_%(class)ss",
1162 )
1163
1164 class Meta:
1165 abstract = True
1166
1167
1168 class ChildA(Base):
1169 pass
1170
1171
1172 class ChildB(Base):
1173 pass
1174
1175 Along with another app ``rare/models.py``::
1176
1177 from common.models import Base
1178
1179
1180 class ChildB(Base):
1181 pass
1182
1183 The reverse name of the ``common.ChildA.m2m`` field will be
1184 ``common_childa_related`` and the reverse query name will be ``common_childas``.
1185 The reverse name of the ``common.ChildB.m2m`` field will be
1186 ``common_childb_related`` and the reverse query name will be
1187 ``common_childbs``. Finally, the reverse name of the ``rare.ChildB.m2m`` field
1188 will be ``rare_childb_related`` and the reverse query name will be
1189 ``rare_childbs``. It's up to you how you use the ``'%(class)s'`` and
1190 ``'%(app_label)s'`` portion to construct your related name or related query name
1191 but if you forget to use it, Django will raise errors when you perform system
1192 checks (or run :djadmin:`migrate`).
1193
1194 If you don't specify a :attr:`~django.db.models.ForeignKey.related_name`
1195 attribute for a field in an abstract base class, the default reverse name will
1196 be the name of the child class followed by ``'_set'``, just as it normally
1197 would be if you'd declared the field directly on the child class. For example,
1198 in the above code, if the :attr:`~django.db.models.ForeignKey.related_name`
1199 attribute was omitted, the reverse name for the ``m2m`` field would be
1200 ``childa_set`` in the ``ChildA`` case and ``childb_set`` for the ``ChildB``
1201 field.
1202
1203 .. _multi-table-inheritance:
1204
1205 Multi-table inheritance
1206 -----------------------
1207
1208 The second type of model inheritance supported by Django is when each model in
1209 the hierarchy is a model all by itself. Each model corresponds to its own
1210 database table and can be queried and created individually. The inheritance
1211 relationship introduces links between the child model and each of its parents
1212 (via an automatically-created :class:`~django.db.models.OneToOneField`).
1213 For example::
1214
1215 from django.db import models
1216
1217
1218 class Place(models.Model):
1219 name = models.CharField(max_length=50)
1220 address = models.CharField(max_length=80)
1221
1222
1223 class Restaurant(Place):
1224 serves_hot_dogs = models.BooleanField(default=False)
1225 serves_pizza = models.BooleanField(default=False)
1226
1227 All of the fields of ``Place`` will also be available in ``Restaurant``,
1228 although the data will reside in a different database table. So these are both
1229 possible:
1230
1231 .. code-block:: pycon
1232
1233 >>> Place.objects.filter(name="Bob's Cafe")
1234 >>> Restaurant.objects.filter(name="Bob's Cafe")
1235
1236 If you have a ``Place`` that is also a ``Restaurant``, you can get from the
1237 ``Place`` object to the ``Restaurant`` object by using the lowercase version of
1238 the model name:
1239
1240 .. code-block:: pycon
1241
1242 >>> p = Place.objects.get(id=12)
1243 # If p is a Restaurant object, this will give the child class:
1244 >>> p.restaurant
1245 <Restaurant: ...>
1246
1247 However, if ``p`` in the above example was *not* a ``Restaurant`` (it had been
1248 created directly as a ``Place`` object or was the parent of some other class),
1249 referring to ``p.restaurant`` would raise a ``Restaurant.DoesNotExist``
1250 exception.
1251
1252 The automatically-created :class:`~django.db.models.OneToOneField` on
1253 ``Restaurant`` that links it to ``Place`` looks like this::
1254
1255 place_ptr = models.OneToOneField(
1256 Place,
1257 on_delete=models.CASCADE,
1258 parent_link=True,
1259 primary_key=True,
1260 )
1261
1262 You can override that field by declaring your own
1263 :class:`~django.db.models.OneToOneField` with :attr:`parent_link=True
1264 <django.db.models.OneToOneField.parent_link>` on ``Restaurant``.
1265
1266 .. _meta-and-multi-table-inheritance:
1267
1268 ``Meta`` and multi-table inheritance
1269 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1270
1271 In the multi-table inheritance situation, it doesn't make sense for a child
1272 class to inherit from its parent's :ref:`Meta <meta-options>` class. All the :ref:`Meta <meta-options>` options
1273 have already been applied to the parent class and applying them again would
1274 normally only lead to contradictory behavior (this is in contrast with the
1275 abstract base class case, where the base class doesn't exist in its own
1276 right).
1277
1278 So a child model does not have access to its parent's :ref:`Meta
1279 <meta-options>` class. However, there are a few limited cases where the child
1280 inherits behavior from the parent: if the child does not specify an
1281 :attr:`~django.db.models.Options.ordering` attribute or a
1282 :attr:`~django.db.models.Options.get_latest_by` attribute, it will inherit
1283 these from its parent.
1284
1285 If the parent has an ordering and you don't want the child to have any natural
1286 ordering, you can explicitly disable it::
1287
1288 class ChildModel(ParentModel):
1289 # ...
1290 class Meta:
1291 # Remove parent's ordering effect
1292 ordering = []
1293
1294 Inheritance and reverse relations
1295 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1296
1297 Because multi-table inheritance uses an implicit
1298 :class:`~django.db.models.OneToOneField` to link the child and
1299 the parent, it's possible to move from the parent down to the child,
1300 as in the above example. However, this uses up the name that is the
1301 default :attr:`~django.db.models.ForeignKey.related_name` value for
1302 :class:`~django.db.models.ForeignKey` and
1303 :class:`~django.db.models.ManyToManyField` relations. If you
1304 are putting those types of relations on a subclass of the parent model, you
1305 **must** specify the :attr:`~django.db.models.ForeignKey.related_name`
1306 attribute on each such field. If you forget, Django will raise a validation
1307 error.
1308
1309 For example, using the above ``Place`` class again, let's create another
1310 subclass with a :class:`~django.db.models.ManyToManyField`::
1311
1312 class Supplier(Place):
1313 customers = models.ManyToManyField(Place)
1314
1315 This results in the error:
1316
1317 .. code-block:: pytb
1318
1319 Reverse query name for 'Supplier.customers' clashes with reverse query
1320 name for 'Supplier.place_ptr'.
1321
1322 HINT: Add or change a related_name argument to the definition for
1323 'Supplier.customers' or 'Supplier.place_ptr'.
1324
1325 Adding ``related_name`` to the ``customers`` field as follows would resolve the
1326 error: ``models.ManyToManyField(Place, related_name='provider')``.
1327
1328 Specifying the parent link field
1329 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1330
1331 As mentioned, Django will automatically create a
1332 :class:`~django.db.models.OneToOneField` linking your child
1333 class back to any non-abstract parent models. If you want to control the
1334 name of the attribute linking back to the parent, you can create your
1335 own :class:`~django.db.models.OneToOneField` and set
1336 :attr:`parent_link=True <django.db.models.OneToOneField.parent_link>`
1337 to indicate that your field is the link back to the parent class.
1338
1339 .. _proxy-models:
1340
1341 Proxy models
1342 ------------
1343
1344 When using :ref:`multi-table inheritance <multi-table-inheritance>`, a new
1345 database table is created for each subclass of a model. This is usually the
1346 desired behavior, since the subclass needs a place to store any additional
1347 data fields that are not present on the base class. Sometimes, however, you
1348 only want to change the Python behavior of a model -- perhaps to change the
1349 default manager, or add a new method.
1350
1351 This is what proxy model inheritance is for: creating a *proxy* for the
1352 original model. You can create, delete and update instances of the proxy model
1353 and all the data will be saved as if you were using the original (non-proxied)
1354 model. The difference is that you can change things like the default model
1355 ordering or the default manager in the proxy, without having to alter the
1356 original.
1357
1358 Proxy models are declared like normal models. You tell Django that it's a
1359 proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of
1360 the ``Meta`` class to ``True``.
1361
1362 For example, suppose you want to add a method to the ``Person`` model. You can do it like this::
1363
1364 from django.db import models
1365
1366
1367 class Person(models.Model):
1368 first_name = models.CharField(max_length=30)
1369 last_name = models.CharField(max_length=30)
1370
1371
1372 class MyPerson(Person):
1373 class Meta:
1374 proxy = True
1375
1376 def do_something(self):
1377 # ...
1378 pass
1379
1380 The ``MyPerson`` class operates on the same database table as its parent
1381 ``Person`` class. In particular, any new instances of ``Person`` will also be
1382 accessible through ``MyPerson``, and vice-versa:
1383
1384 .. code-block:: pycon
1385
1386 >>> p = Person.objects.create(first_name="foobar")
1387 >>> MyPerson.objects.get(first_name="foobar")
1388 <MyPerson: foobar>
1389
1390 You could also use a proxy model to define a different default ordering on
1391 a model. You might not always want to order the ``Person`` model, but regularly
1392 order by the ``last_name`` attribute when you use the proxy::
1393
1394 class OrderedPerson(Person):
1395 class Meta:
1396 ordering = ["last_name"]
1397 proxy = True
1398
1399 Now normal ``Person`` queries will be unordered
1400 and ``OrderedPerson`` queries will be ordered by ``last_name``.
1401
1402 Proxy models inherit ``Meta`` attributes :ref:`in the same way as regular
1403 models <meta-and-multi-table-inheritance>`.
1404
1405 ``QuerySet``\s still return the model that was requested
1406 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1407
1408 There is no way to have Django return, say, a ``MyPerson`` object whenever you
1409 query for ``Person`` objects. A queryset for ``Person`` objects will return
1410 those types of objects. The whole point of proxy objects is that code relying
1411 on the original ``Person`` will use those and your own code can use the
1412 extensions you included (that no other code is relying on anyway). It is not
1413 a way to replace the ``Person`` (or any other) model everywhere with something
1414 of your own creation.
1415
1416 Base class restrictions
1417 ~~~~~~~~~~~~~~~~~~~~~~~
1418
1419 A proxy model must inherit from exactly one non-abstract model class. You
1420 can't inherit from multiple non-abstract models as the proxy model doesn't
1421 provide any connection between the rows in the different database tables. A
1422 proxy model can inherit from any number of abstract model classes, providing
1423 they do *not* define any model fields. A proxy model may also inherit from any
1424 number of proxy models that share a common non-abstract parent class.
1425
1426 Proxy model managers
1427 ~~~~~~~~~~~~~~~~~~~~
1428
1429 If you don't specify any model managers on a proxy model, it inherits the
1430 managers from its model parents. If you define a manager on the proxy model,
1431 it will become the default, although any managers defined on the parent
1432 classes will still be available.
1433
1434 Continuing our example from above, you could change the default manager used
1435 when you query the ``Person`` model like this::
1436
1437 from django.db import models
1438
1439
1440 class NewManager(models.Manager):
1441 # ...
1442 pass
1443
1444
1445 class MyPerson(Person):
1446 objects = NewManager()
1447
1448 class Meta:
1449 proxy = True
1450
1451 If you wanted to add a new manager to the Proxy, without replacing the
1452 existing default, you can use the techniques described in the :ref:`custom
1453 manager <custom-managers-and-inheritance>` documentation: create a base class
1454 containing the new managers and inherit that after the primary base class::
1455
1456 # Create an abstract class for the new manager.
1457 class ExtraManagers(models.Model):
1458 secondary = NewManager()
1459
1460 class Meta:
1461 abstract = True
1462
1463
1464 class MyPerson(Person, ExtraManagers):
1465 class Meta:
1466 proxy = True
1467
1468 You probably won't need to do this very often, but, when you do, it's
1469 possible.
1470
1471 .. _proxy-vs-unmanaged-models:
1472
1473 Differences between proxy inheritance and unmanaged models
1474 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1475
1476 Proxy model inheritance might look fairly similar to creating an unmanaged
1477 model, using the :attr:`~django.db.models.Options.managed` attribute on a
1478 model's ``Meta`` class.
1479
1480 With careful setting of :attr:`Meta.db_table
1481 <django.db.models.Options.db_table>` you could create an unmanaged model that
1482 shadows an existing model and adds Python methods to it. However, that would be
1483 very repetitive and fragile as you need to keep both copies synchronized if you
1484 make any changes.
1485
1486 On the other hand, proxy models are intended to behave exactly like the model
1487 they are proxying for. They are always in sync with the parent model since they
1488 directly inherit its fields and managers.
1489
1490 The general rules are:
1491
1492 #. If you are mirroring an existing model or database table and don't want
1493 all the original database table columns, use ``Meta.managed=False``.
1494 That option is normally useful for modeling database views and tables
1495 not under the control of Django.
1496 #. If you are wanting to change the Python-only behavior of a model, but
1497 keep all the same fields as in the original, use ``Meta.proxy=True``.
1498 This sets things up so that the proxy model is an exact copy of the
1499 storage structure of the original model when data is saved.
1500
1501 .. _model-multiple-inheritance-topic:
1502
1503 Multiple inheritance
1504 --------------------
1505
1506 Just as with Python's subclassing, it's possible for a Django model to inherit
1507 from multiple parent models. Keep in mind that normal Python name resolution
1508 rules apply. The first base class that a particular name (e.g. :ref:`Meta
1509 <meta-options>`) appears in will be the one that is used; for example, this
1510 means that if multiple parents contain a :ref:`Meta <meta-options>` class,
1511 only the first one is going to be used, and all others will be ignored.
1512
1513 Generally, you won't need to inherit from multiple parents. The main use-case
1514 where this is useful is for "mix-in" classes: adding a particular extra
1515 field or method to every class that inherits the mix-in. Try to keep your
1516 inheritance hierarchies as simple and straightforward as possible so that you
1517 won't have to struggle to work out where a particular piece of information is
1518 coming from.
1519
1520 Note that inheriting from multiple models that have a common ``id`` primary
1521 key field will raise an error. To properly use multiple inheritance, you can
1522 use an explicit :class:`~django.db.models.AutoField` in the base models::
1523
1524 class Article(models.Model):
1525 article_id = models.AutoField(primary_key=True)
1526 ...
1527
1528
1529 class Book(models.Model):
1530 book_id = models.AutoField(primary_key=True)
1531 ...
1532
1533
1534 class BookReview(Book, Article):
1535 pass
1536
1537 Or use a common ancestor to hold the :class:`~django.db.models.AutoField`. This
1538 requires using an explicit :class:`~django.db.models.OneToOneField` from each
1539 parent model to the common ancestor to avoid a clash between the fields that
1540 are automatically generated and inherited by the child::
1541
1542 class Piece(models.Model):
1543 pass
1544
1545
1546 class Article(Piece):
1547 article_piece = models.OneToOneField(
1548 Piece, on_delete=models.CASCADE, parent_link=True
1549 )
1550 ...
1551
1552
1553 class Book(Piece):
1554 book_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)
1555 ...
1556
1557
1558 class BookReview(Book, Article):
1559 pass
1560
1561 Field name "hiding" is not permitted
1562 ------------------------------------
1563
1564 In normal Python class inheritance, it is permissible for a child class to
1565 override any attribute from the parent class. In Django, this isn't usually
1566 permitted for model fields. If a non-abstract model base class has a field
1567 called ``author``, you can't create another model field or define
1568 an attribute called ``author`` in any class that inherits from that base class.
1569
1570 This restriction doesn't apply to model fields inherited from an abstract
1571 model. Such fields may be overridden with another field or value, or be removed
1572 by setting ``field_name = None``.
1573
1574 .. warning::
1575
1576 Model managers are inherited from abstract base classes. Overriding an
1577 inherited field which is referenced by an inherited
1578 :class:`~django.db.models.Manager` may cause subtle bugs. See :ref:`custom
1579 managers and model inheritance <custom-managers-and-inheritance>`.
1580
1581 .. note::
1582
1583 Some fields define extra attributes on the model, e.g. a
1584 :class:`~django.db.models.ForeignKey` defines an extra attribute with
1585 ``_id`` appended to the field name, as well as ``related_name`` and
1586 ``related_query_name`` on the foreign model.
1587
1588 These extra attributes cannot be overridden unless the field that defines
1589 it is changed or removed so that it no longer defines the extra attribute.
1590
1591 Overriding fields in a parent model leads to difficulties in areas such as
1592 initializing new instances (specifying which field is being initialized in
1593 ``Model.__init__``) and serialization. These are features which normal Python
1594 class inheritance doesn't have to deal with in quite the same way, so the
1595 difference between Django model inheritance and Python class inheritance isn't
1596 arbitrary.
1597
1598 This restriction only applies to attributes which are
1599 :class:`~django.db.models.Field` instances. Normal Python attributes
1600 can be overridden if you wish. It also only applies to the name of the
1601 attribute as Python sees it: if you are manually specifying the database
1602 column name, you can have the same column name appearing in both a child and
1603 an ancestor model for multi-table inheritance (they are columns in two
1604 different database tables).
1605
1606 Django will raise a :exc:`~django.core.exceptions.FieldError` if you override
1607 any model field in any ancestor model.
1608
1609 Note that because of the way fields are resolved during class definition, model
1610 fields inherited from multiple abstract parent models are resolved in a strict
1611 depth-first order. This contrasts with standard Python MRO, which is resolved
1612 breadth-first in cases of diamond shaped inheritance. This difference only
1613 affects complex model hierarchies, which (as per the advice above) you should
1614 try to avoid.
1615
1616 Organizing models in a package
1617 ==============================
1618
1619 The :djadmin:`manage.py startapp <startapp>` command creates an application
1620 structure that includes a ``models.py`` file. If you have many models,
1621 organizing them in separate files may be useful.
1622
1623 To do so, create a ``models`` package. Remove ``models.py`` and create a
1624 ``myapp/models/`` directory with an ``__init__.py`` file and the files to
1625 store your models. You must import the models in the ``__init__.py`` file.
1626
1627 For example, if you had ``organic.py`` and ``synthetic.py`` in the ``models``
1628 directory:
1629
1630 .. code-block:: python
1631 :caption: ``myapp/models/__init__.py``
1632
1633 from .organic import Person
1634 from .synthetic import Robot
1635
1636 Explicitly importing each model rather than using ``from .models import *``
1637 has the advantages of not cluttering the namespace, making code more readable,
1638 and keeping code analysis tools useful.
1639
1640 .. seealso::
1641
1642 :doc:`The Models Reference </ref/models/index>`
1643 Covers all the model related APIs including model fields, related
1644 objects, and ``QuerySet``.