模型

模型是您的数据唯一而且准确的信息来源。它包含您正在储存的数据的重要字段和行为。一般来说,每一个模型都映射一个数据库表。

基础:

  • 每个模型都是一个 Python 的类,这些类继承 django.db.models.Model
  • 模型类的每个属性都相当于一个数据库的字段。
  • 综上诉说,Django 给你一个自动生成访问数据库的 API;请参阅 进行查询

快速上手

这个样例模型定义了一个 Person, 其拥有 first_namelast_name:

  1. from django.db import models
  2.  
  3. class Person(models.Model):
  4. first_name = models.CharField(max_length=30)
  5. last_name = models.CharField(max_length=30)

first_namelast_name 是模型的字段。每个字段都被指定为一个类属性,并且每个属性映射为一个数据库列。

上面的 Person 模型会创建一个如下的数据库表:

  1. CREATE TABLE myapp_person (
  2. "id" serial NOT NULL PRIMARY KEY,
  3. "first_name" varchar(30) NOT NULL,
  4. "last_name" varchar(30) NOT NULL
  5. );

一些技术上的说明:

  • 该表的名称 “myapp_person” 是自动从某些模型元数据中派生出来,但可以被改写。有关更多详细信息,请参阅:表命名。
  • 一个 id 字段会被自动添加,但是这种行为可以被改写。请参阅:默认主键字段。
  • The CREATE TABLE SQL in this example is formatted using PostgreSQLsyntax, but it's worth noting Django uses SQL tailored to the databasebackend specified in your settings file.

使用模型

一旦你定义了你的模型,你需要告诉 Django 你准备使用这些模型。你需要修改设置文件中的 INSTALLED_APPS ,在这个设置中添加包含你 models.py 文件的模块的名字。

例如,如果模型位于你项目中的myapp.models中( 此包结构使用:djadmin:manage.py startapp命令创建),:setting:INSTALLED_APPS 应设置如下:

  1. INSTALLED_APPS = [
  2. #...
  3. 'myapp',
  4. #...
  5. ]

当你向 INSTALLED_APPS 添加新的应用的时候,请务必运行:djadmin:manage.py migrate <migrate>,此外你也可以先使用以下命令先进行迁移 manage.py makemigrations

字段

模型中最重要的、并且也是唯一必须的是数据库的字段定义。字段在类中定义。定义字段名时应小心避免使用与 models API</ref/models/instances>冲突的名称, 如 clean`, <code>save</code>, or [](#id1)delete``等.

举例:

  1. from django.db import models
  2.  
  3. class Musician(models.Model):
  4. first_name = models.CharField(max_length=50)
  5. last_name = models.CharField(max_length=50)
  6. instrument = models.CharField(max_length=100)
  7.  
  8. class Album(models.Model):
  9. artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
  10. name = models.CharField(max_length=100)
  11. release_date = models.DateField()
  12. num_stars = models.IntegerField()

字段类型

模型中每一个字段都应该是相应类的实例, Django 利用这些字段类来实现下面这些功能。

  • 字段类型用以指定数据库数据类型(如:INTEGER, VARCHAR, TEXT
  • 默认的HTML表单输入框(如: Django内置了多种字段类型;你可以在模型字段参考<model-field-types>中看到完整列表。如果Django内置类型不能满足你的需求,你可以很轻松地编写自定义的字段类型;见:doc:/howto/custom-model-fields

字段选项

每一种字段都需要指定一些特定的参数(参考 model field reference<model-field-types> ) 例如: :class:`~django.db.models.CharField (以及它的子类)需要接收一个 max_length 参数,用以指定数据库存储数据时用的 VARCHAR 大小。

一些可选的参数是通用的,可以用于任何字段类型,详情请见 :ref:`reference<common-model-field-options> ` ,下面介绍一部分经常用到的通用参数:

  • null
  • 如果设置为 True , 当该字段为空时,Django会将数据库中该字段设置为 NULL 。默认为 False
  • blank
  • 如果设置为 True ,该字段允许为空。默认为 False

注意该选项与 False 不同, null 选项仅仅是数据库层面的设置,然而 blank 是涉及表单验证方面。如果一个字段设置为 blank=True ,在进行表单验证时,接收的数据该字段值允许为空,而设置为 blank=False 时,不允许为空。

  • choices
  • 该参数接收一个可迭代的列表或元组(基本单位为二元组)。如果指定了该参数,在实例化该模型时,该字段只能取选项列表中的值。

一个选项列表:

  1. YEAR_IN_SCHOOL_CHOICES = (
  2. ('FR', 'Freshman'),
  3. ('SO', 'Sophomore'),
  4. ('JR', 'Junior'),
  5. ('SR', 'Senior'),
  6. ('GR', 'Graduate'),
  7. )

每个二元组的第一个值会储存在数据库中,而第二个值将只会用于显示作用。

对于一个模型实例,要获取该字段二元组中相对应的第二个值,使用 get_FOO_display() 方法。例如:

  1. from django.db import models
  2.  
  3. class Person(models.Model):
  4. SHIRT_SIZES = (
  5. ('S', 'Small'),
  6. ('M', 'Medium'),
  7. ('L', 'Large'),
  8. )
  9. name = models.CharField(max_length=60)
  10. shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
  1. >>> p = Person(name="Fred Flintstone", shirt_size="L")
  2. >>> p.save()
  3. >>> p.shirt_size
  4. 'L'
  5. >>> p.get_shirt_size_display()
  6. 'Large'
  • default
  • 该字段的默认值。可以是一个值或者是个可调用的对象,如果是个可调用对象,每次实例化模型时都会调用该对象。
  • help_text
  • Extra "help" text to be displayed with the form widget. It's useful fordocumentation even if your field isn't used on a form.
  • primary_key
  • 如果设置为 True ,将该字段设置为该模型的主键。

在一个模型中,如果你没有对任何一个字段设置 primary_key=True 选项。 Django 会自动添加一个 IntegerField 字段,用于设置为主键,因此除非你想重写 Django 默认的主键设置行为,你可以不手动设置主键。详情请见 自动设置主键

主键字段是只可读的,如果你修改一个模型实例该字段的值并保存,你将等同于创建了一个新的模型实例。例如:

  1. from django.db import models
  2.  
  3. class Fruit(models.Model):
  4. name = models.CharField(max_length=100, primary_key=True)
  1. >>> fruit = Fruit.objects.create(name='Apple')
  2. >>> fruit.name = 'Pear'
  3. >>> fruit.save()
  4. >>> Fruit.objects.values_list('name', flat=True)
  5. <QuerySet ['Apple', 'Pear']>
  • unique
  • 如果设置为 True,这个字段必须在整个表中保持值唯一。 再次声明,以上只是一些通用参数的简略描述。你可以在 :ref:`common model field option reference<common-model-field-options> ` 中找到完整的介绍。

自动设置主键

默认情况下, Django 会给每一个模型添加下面的字段:

  1. id = models.AutoField(primary_key=True)

这是一个自增的主键。

如果你想指定设置为为主键的字段, 在你想要设置为主键的字段上设置 primary_key=True 选项。如果 Django 看到你显式的设置了 Field.primary_key ,将不会自动在表(模型)中添加 id 列。

每个模型都需要拥有一个设置了 primary_key=True 的字段(无论是显式的设置还是 Django 自动设置)。

备注名

除了 ForeignKeyManyToManyFieldOneToOneField ,任何字段类型都接收一个可选的参数 verbose_name ,如果未指定该参数值, Django 会自动使用该字段的属性名作为该参数值,并且把下划线转换为空格。

在该例中:备注名为 "person's first name":: 。

  1. first_name = models.CharField("person's first name", max_length=30)

在该例中:备注名为 "first name":: 。

  1. first_name = models.CharField(max_length=30)

ForeignKey, ManyToManyField and OneToOneField 接收的第一个参数为模型的类名,后面可以添加一个 verbose_name 参数:

  1. poll = models.ForeignKey(
  2. Poll,
  3. on_delete=models.CASCADE,
  4. verbose_name="the related poll",
  5. )
  6. sites = models.ManyToManyField(Site, verbose_name="list of sites")
  7. place = models.OneToOneField(
  8. Place,
  9. on_delete=models.CASCADE,
  10. verbose_name="related place",
  11. )

一般情况下不需要将 verbose_name 值首字母大写,必要时 Djanog 会自动把首字母转换为大写。

关联关系

显然,关系型数据库的强大之处在于各表之间的关联关系。 Django 提供了定义三种最常见的数据库关联关系的方法:多对一,多对多,一对一。

Many-to-one relationships

定义一个多对一的关联关系,使用 django.db.models.ForeignKey 类。就和其他 Field 字段类型一样,只需要在你模型中添加一个值为该类的属性。

ForeignKey requires a positional argument: the classto which the model is related.

例如,如果一个 Car 模型 有一个制造者 Manufacturer —就是说一个 Manufacturer 制造许多辆车,但是每辆车都属于某个特定的制造者— 那么使用下面的方法定义这个关系:

  1. from django.db import models
  2.  
  3. class Manufacturer(models.Model):
  4. # ...
  5. pass
  6.  
  7. class Car(models.Model):
  8. manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
  9. # ...

你也可以创建一个 recursive relationships 关系(一个模型与它本身有多对一的关系)和 :ref:`relationships to models not yet defined <lazy-relationships> ;详情请见 :ref:[](#id3)the model field reference <ref-foreignkey> ` 。

建议设置 ForeignKey 字段(上例中的 manufacturer )名为想要关联的模型名,但是你也可以随意设置为你想要的名称,例如:

  1. class Car(models.Model):
  2. company_that_makes_it = models.ForeignKey(
  3. Manufacturer,
  4. on_delete=models.CASCADE,
  5. )
  6. # ...

参见

ForeignKey 字段还可以接收一些其他的参数,详见 the model field reference ,这些可选的参数可以更深入的规定光联关系的具体实现。

For details on accessing backwards-related objects, see theFollowing relationships backward example.

如要查看相关示例代码,详见 :doc:`Many-to-one relationship model example </topics/db/examples/many_to_one> ` 。

Many-to-many relationships

定义一个多对多的关联关系,使用 django.db.models.ManyToManyField 类。就和其他 Field 字段类型一样,只需要在你模型中添加一个值为该类的属性。

ManyToManyField requires a positional argument: theclass to which the model is related.

例如:如果 Pizza 含有多种 Topping(配料) -- 也就是一种Topping 可能存在于多个 Pizza 中,并且每个 Pizza 含有多种 Topping —那么可以这样表示这种关系:

  1. from django.db import models
  2.  
  3. class Topping(models.Model):
  4. # ...
  5. pass
  6.  
  7. class Pizza(models.Model):
  8. # ...
  9. toppings = models.ManyToManyField(Topping)

ForeignKey 类一样,你也可以创建 recursive relationships 关系(一个对象与他本身有着多对多的关系)和 relationships to models not yet defined 关系。

建议设置 ManyToManyField 字段(上例中的 toppings )名为一个复数名词,表示所要光联的模型对象的集合。

对于多对多光联关系的两个模型,可以在任何一个模型中添加 ManyToManyField 字段,但只能选择一个模型设置该字段,即不能同时在两模型中添加该字段。

一般来讲,应该把 ManyToManyField 实例放到需要在表单中被编辑的对象中。在之前的例子中, toppings 被放在 Pizza 当中(而不是 Topping 中有指向 pizzasManyToManyField 实例 )因为相较于配料被放在不同的披萨当中,披萨当中有很多种配料更加符合常理。按照先前说的,在编辑 Pizza 的表单时用户可以选择多种配料。

参见

如要查看完整示例代码,详见 Many-to-many relationship model example

ManyToManyField fields also accept a number ofextra arguments which are explained in the model field reference. These options help define how the relationshipshould work; all are optional.

在多对多(many-to-many)关系中添加添加额外的属性字段

如果你只是想要一个类似于记录披萨和配料之间混合和搭配的简单多对多关系,标准的 ManyToManyField 就足够你用了。然而,有的时候你可能会需要在两个模型的关系中记录更多的数据。

举例来讲,考虑一个需要跟踪音乐人属于哪个音乐组的应用程序。在人和他们所在的组之间有一个多对多关系,你可以使用 ManyToManyField 来代表这个关系。然而,你想要记录更多的信息在这样的所属关系当中,比如你想要记录某人是何时加入一个组的。

对于这些情况,Django允许你指定用于控制多对多关系的模型。你可以在中间模型当中添加而外的字段。在实例化 ManyToManyField 的时候使用 through 参数指定多对多关系使用哪个中间模型。对于我们举的音乐家的例子,代码如下:

  1. from django.db import models
  2.  
  3. class Person(models.Model):
  4. name = models.CharField(max_length=128)
  5.  
  6. def __str__(self):
  7. return self.name
  8.  
  9. class Group(models.Model):
  10. name = models.CharField(max_length=128)
  11. members = models.ManyToManyField(Person, through='Membership')
  12.  
  13. def __str__(self):
  14. return self.name
  15.  
  16. class Membership(models.Model):
  17. person = models.ForeignKey(Person, on_delete=models.CASCADE)
  18. group = models.ForeignKey(Group, on_delete=models.CASCADE)
  19. date_joined = models.DateField()
  20. invite_reason = models.CharField(max_length=64)

在设置中间模型的时候,你需要显式地为多对多关系中涉及的模型指定外键。这种显式声明定义了这两个模型之间的关系。

在中间模型当中有一些限制条件:

  • 你的中间模型要么有且 有一个指向源模型(我们例子当中的 Group )的外键,要么你必须通过 ManyToManyField.through_fields 参数在多个外键当中手动选择一个外键,如果有多个外健且没有用 through_fields 参数选择一个的话,会出现验证错误。对于指向目标模型(我们例子当中的 Person )的外键也有同样的限制。
  • 在一个用于描述模型当中自己指向自己的多对多关系的中间模型当中,可以有两个指向同一个模型的外健,但这两个外健分表代表多对多关系(不同)的两端。如果外健的个数 超过 两个,你必须和上面一样指定 through_fields 参数,要不然会出现验证错误。
  • 在定义模型自己指向自己的多对多关系时,如果使用中间模型,你 必须 定义 symmetrical=False (查看 the model field reference)。 现在你已经通过中间模型完成你的 ManyToManyField (例子中的Membership),可以开始创建一些多对多关系了。你通过实例化中间模型来创建关系:
  1. >>> ringo = Person.objects.create(name="Ringo Starr")
  2. >>> paul = Person.objects.create(name="Paul McCartney")
  3. >>> beatles = Group.objects.create(name="The Beatles")
  4. >>> m1 = Membership(person=ringo, group=beatles,
  5. ... date_joined=date(1962, 8, 16),
  6. ... invite_reason="Needed a new drummer.")
  7. >>> m1.save()
  8. >>> beatles.members.all()
  9. <QuerySet [<Person: Ringo Starr>]>
  10. >>> ringo.group_set.all()
  11. <QuerySet [<Group: The Beatles>]>
  12. >>> m2 = Membership.objects.create(person=paul, group=beatles,
  13. ... date_joined=date(1960, 8, 1),
  14. ... invite_reason="Wanted to form a band.")
  15. >>> beatles.members.all()
  16. <QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>]>

You can also use add(), create(), or set() to create relationships,as long as your specify through_defaults for any required fields:

  1. >>> beatles.members.add(john, through_defaults={'date_joined': date(1960, 8, 1)})
  2. >>> beatles.members.create(name="George Harrison", through_defaults={'date_joined': date(1960, 8, 1)})
  3. >>> beatles.members.set([john, paul, ringo, george], through_defaults={'date_joined': date(1960, 8, 1)})

You may prefer to create instances of the intermediate model directly.

If the custom through table defined by the intermediate model does not enforceuniqueness on the (model1, model2) pair, allowing multiple values, theremove() call willremove all intermediate model instances:

  1. >>> Membership.objects.create(person=ringo, group=beatles,
  2. ... date_joined=date(1968, 9, 4),
  3. ... invite_reason="You've been gone for a month and we miss you.")
  4. >>> beatles.members.all()
  5. <QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>, <Person: Ringo Starr>]>
  6. >>> # This deletes both of the intermediate model instances for Ringo Starr
  7. >>> beatles.members.remove(ringo)
  8. >>> beatles.members.all()
  9. <QuerySet [<Person: Paul McCartney>]>

The clear()method can be used to remove all many-to-many relationships for an instance:

  1. >>> # Beatles have broken up
  2. >>> beatles.members.clear()
  3. >>> # Note that this deletes the intermediate model instances
  4. >>> Membership.objects.all()
  5. <QuerySet []>

Once you have established the many-to-many relationships, you can issuequeries. Just as with normal many-to-many relationships, you can query usingthe attributes of the many-to-many-related model:

  1. # Find all the groups with a member whose name starts with 'Paul'
  2. >>> Group.objects.filter(members__name__startswith='Paul')
  3. <QuerySet [<Group: The Beatles>]>

当你使用中间模型的时候,你也可以查询他的属性:

  1. # Find all the members of the Beatles that joined after 1 Jan 1961
  2. >>> Person.objects.filter(
  3. ... group__name='The Beatles',
  4. ... membership__date_joined__gt=date(1961,1,1))
  5. <QuerySet [<Person: Ringo Starr]>

如果你想访问一个关系的信息时你可以直接查询 Membership 模型:

  1. >>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
  2. >>> ringos_membership.date_joined
  3. datetime.date(1962, 8, 16)
  4. >>> ringos_membership.invite_reason
  5. 'Needed a new drummer.'

另一种访问同样信息的方法是通过 Person 对象来查询 ref:many-to-many reverse relationship<m2m-reverse-relationships>

  1. >>> ringos_membership = ringo.membership_set.get(group=beatles)
  2. >>> ringos_membership.date_joined
  3. datetime.date(1962, 8, 16)
  4. >>> ringos_membership.invite_reason
  5. 'Needed a new drummer.'

One-to-one relationships

使用 OneToOneField 来定义一对一关系。就像使用其他类型的 Field 一样:在模型属性中包含它。

当一个对象以某种方式“扩展”另一个对象时,这对该对象的主键非常有用。

OneToOneField 需要一个位置参数:与模型相关的类。

例如,当你要建立一个有关“位置”信息的数据库时,你可能会包含通常的地址,电话等字段。接着,如果你想接着建立一个关于关于餐厅的数据库,除了将位置数据库当中的字段复制到 Restaurant 模型,你也可以将一个指向 Place OneToOneField 放到 Restaurant 当中(因为餐厅“是一个”地点);事实上,在处理这样的情况时最好使用 inheritance ,它隐含的包括了一个一对一关系。

ForeignKey 一样,可以创建 recursive relationship 也可以创建 references to as-yet undefined models

参见

点击文档 One-to-one relationship model example 来查看完整的例子。

OneToOneField 字段还接受一个可选的 parent_link 参数。

OneToOneField 类通常自动的成为模型的主键,这条规则现在不再使用了(然而你可以手动指定 primary_key 参数)。因此,现在可以在单个模型当中指定多个 OneToOneField 字段。

跨文件模型

关联另一个应用中的模型是当然可以的。为了实现这一点,在定义模型的文件开头导入需要被关联的模型。接着,接着就可以在其他有需要的模型类当中关联它了。比如:

  1. from django.db import models
  2. from geography.models import ZipCode
  3.  
  4. class Restaurant(models.Model):
  5. # ...
  6. zip_code = models.ForeignKey(
  7. ZipCode,
  8. on_delete=models.SET_NULL,
  9. blank=True,
  10. null=True,
  11. )

字段命名限制

Django places some restrictions on model field names:

  • 一个字段的名称不能是Python保留字,因为这回导致Python语法错误。比如:
  1. class Example(models.Model):
  2. pass = models.IntegerField() # 'pass' is a reserved word!
  • 一个字段名称不能包含连续的多个下划线,原因在于Django查询语法的工作方式。比如:
  1. class Example(models.Model):
  2. foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
  • A field name cannot end with an underscore, for similar reasons.

但是,这些限制是可以被解决的,因为字段名没要求和数据库列名一样。查看 db_column 选项。

SQL保留字,例如 joinwhereselect 可以被用在模型字段名当中的,因为Django在对底层的SQL查询当中清洗了所有的数据库表名和字段名,通过使用特定数据库引擎的引用语法。

自定义的字段类型

如果已经存在的模型字段不能满足你的需求,或者你希望支持一些不太常见的数据库列类型,你可以创建自己的字段类。在 :doc:`/howto/custom-model-fields 中提供了创建自己的字段的各方面内容。

Meta 选项

使用内部 Meta类 来给模型赋予元数据,就像:

  1. from django.db import models
  2.  
  3. class Ox(models.Model):
  4. horn_length = models.IntegerField()
  5.  
  6. class Meta:
  7. ordering = ["horn_length"]
  8. verbose_name_plural = "oxen"

模型的元数据是指“所有不是字段的东西”,比如排序选项(attr:~Options.ordering),数据库表名(db_table),或是人可读的单复数名(verbose_nameverbose_name_plural)。都不是必须的,并且在模型当中添加 Meta类 也完全是可选的。

model option reference 中列出了 Meta 可使用的全部选项。

模型属性

  • objects
  • 模型当中最重要的属性是 Manager。它是Django模型和数据库查询操作之间的接口,并且它被用作从数据库当中 retrieve the instances,如果没有指定自定义的 Manager 默认名称是 objects。Manager只能通过模型类来访问,不能通过模型实例来访问。

模型方法

Define custom methods on a model to add custom "row-level" functionality to yourobjects. Whereas Manager methods are intended to do"table-wide" things, model methods should act on a particular model instance.

This is a valuable technique for keeping business logic in one place — themodel.

For example, this model has a few custom methods:

  1. from django.db import models
  2.  
  3. class Person(models.Model):
  4. first_name = models.CharField(max_length=50)
  5. last_name = models.CharField(max_length=50)
  6. birth_date = models.DateField()
  7.  
  8. def baby_boomer_status(self):
  9. "Returns the person's baby-boomer status."
  10. import datetime
  11. if self.birth_date < datetime.date(1945, 8, 1):
  12. return "Pre-boomer"
  13. elif self.birth_date < datetime.date(1965, 1, 1):
  14. return "Baby boomer"
  15. else:
  16. return "Post-boomer"
  17.  
  18. @property
  19. def full_name(self):
  20. "Returns the person's full name."
  21. return '%s %s' % (self.first_name, self.last_name)

The last method in this example is a property.

The model instance reference has a complete listof methods automatically given to each model.You can override most of these — see overriding predefined model methods,below — but there are a couple that you'll almost always want to define:

  • str()
  • A Python "magic method" that returns a string representation of anyobject. This is what Python and Django will use whenever a modelinstance needs to be coerced and displayed as a plain string. Mostnotably, this happens when you display an object in an interactiveconsole or in the admin.

You'll always want to define this method; the default isn't very helpfulat all.

  • get_absolute_url()
  • This tells Django how to calculate the URL for an object. Django usesthis in its admin interface, and any time it needs to figure out a URLfor an object.

Any object that has a URL that uniquely identifies it should define thismethod.

Overriding predefined model methods

There's another set of model methods thatencapsulate a bunch of database behavior that you'll want to customize. Inparticular you'll often want to change the way save() anddelete() work.

You're free to override these methods (and any other model method) to alterbehavior.

A classic use-case for overriding the built-in methods is if you want somethingto happen whenever you save an object. For example (seesave() for documentation of the parameters it accepts):

  1. from django.db import models
  2.  
  3. class Blog(models.Model):
  4. name = models.CharField(max_length=100)
  5. tagline = models.TextField()
  6.  
  7. def save(self, *args, **kwargs):
  8. do_something()
  9. super().save(*args, **kwargs) # Call the "real" save() method.
  10. do_something_else()

You can also prevent saving:

  1. from django.db import models
  2.  
  3. class Blog(models.Model):
  4. name = models.CharField(max_length=100)
  5. tagline = models.TextField()
  6.  
  7. def save(self, *args, **kwargs):
  8. if self.name == "Yoko Ono's blog":
  9. return # Yoko shall never have her own blog!
  10. else:
  11. super().save(*args, **kwargs) # Call the "real" save() method.

It's important to remember to call the superclass method — that'sthat super().save(args, *kwargs) business — to ensurethat the object still gets saved into the database. If you forget tocall the superclass method, the default behavior won't happen and thedatabase won't get touched.

It's also important that you pass through the arguments that can bepassed to the model method — that's what the args, **kwargs bitdoes. Django will, from time to time, extend the capabilities ofbuilt-in model methods, adding new arguments. If you use args, **kwargs in your method definitions, you are guaranteed that yourcode will automatically support those arguments when they are added.

Overridden model methods are not called on bulk operations

Note that the delete() method for an object is notnecessarily called when deleting objects in bulk using aQuerySet or as a result of a cascading delete. To ensure customizeddelete logic gets executed, you can usepre_delete and/orpost_delete signals.

Unfortunately, there isn't a workaround whencreating orupdating objects in bulk,since none of save(),pre_save, andpost_save are called.

Executing custom SQL

Another common pattern is writing custom SQL statements in model methods andmodule-level methods. For more details on using raw SQL, see the documentationon using raw SQL.

模型继承

模型继承在 Django 中与普通类继承在 Python 中的工作方式几乎完全相同, 但也仍应遵循本页开头的内容. 这意味着其基类应该继承自 django.db.models.Model .

The only decision you have to make is whether you want the parent models to bemodels in their own right (with their own database tables), or if the parentsare just holders of common information that will only be visible through thechild models.

There are three styles of inheritance that are possible in Django.

  • Often, you will just want to use the parent class to hold information thatyou don't want to have to type out for each child model. This class isn'tgoing to ever be used in isolation, so Abstract base classes arewhat you're after.
  • If you're subclassing an existing model (perhaps something from anotherapplication entirely) and want each model to have its own database table,Multi-table inheritance is the way to go.
  • Finally, if you only want to modify the Python-level behavior of a model,without changing the models fields in any way, you can useProxy models.

Abstract base classes

Abstract base classes are useful when you want to put some commoninformation into a number of other models. You write your base classand put abstract=True in the Metaclass. This model will then not be used to create any databasetable. Instead, when it is used as a base class for other models, itsfields will be added to those of the child class.

An example:

  1. from django.db import models
  2.  
  3. class CommonInfo(models.Model):
  4. name = models.CharField(max_length=100)
  5. age = models.PositiveIntegerField()
  6.  
  7. class Meta:
  8. abstract = True
  9.  
  10. class Student(CommonInfo):
  11. home_group = models.CharField(max_length=5)

The Student model will have three fields: name, age andhome_group. The CommonInfo model cannot be used as a normal Djangomodel, since it is an abstract base class. It does not generate a databasetable or have a manager, and cannot be instantiated or saved directly.

Fields inherited from abstract base classes can be overridden with anotherfield or value, or be removed with None.

For many uses, this type of model inheritance will be exactly what you want.It provides a way to factor out common information at the Python level, whilestill only creating one database table per child model at the database level.

Meta inheritance

When an abstract base class is created, Django makes any Metainner class you declared in the base class available as anattribute. If a child class does not declare its own Metaclass, it will inherit the parent's Meta. If the child wants toextend the parent's Meta class, it can subclass it. For example:

  1. from django.db import models
  2.  
  3. class CommonInfo(models.Model):
  4. # ...
  5. class Meta:
  6. abstract = True
  7. ordering = ['name']
  8.  
  9. class Student(CommonInfo):
  10. # ...
  11. class Meta(CommonInfo.Meta):
  12. db_table = 'student_info'

Django does make one adjustment to the Meta class of an abstract baseclass: before installing the Meta attribute, it sets abstract=False.This means that children of abstract base classes don't automatically becomeabstract classes themselves. Of course, you can make an abstract base classthat inherits from another abstract base class. You just need to remember toexplicitly set abstract=True each time.

Some attributes won't make sense to include in the Meta class of anabstract base class. For example, including db_table would mean that allthe child classes (the ones that don't specify their own Meta) would usethe same database table, which is almost certainly not what you want.

If you are using related_name orrelated_query_name on a ForeignKey orManyToManyField, you must always specify a unique reverse name and queryname for the field. This would normally cause a problem in abstract baseclasses, since the fields on this class are included into each of the childclasses, with exactly the same values for the attributes (includingrelated_name andrelated_query_name) each time.

To work around this problem, when you are usingrelated_name orrelated_query_name in an abstract baseclass (only), part of the value should contain '%(app_label)s' and'%(class)s'.

  • '%(class)s' is replaced by the lowercased name of the child class thatthe field is used in.
  • '%(app_label)s' is replaced by the lowercased name of the app the childclass is contained within. Each installed application name must be unique andthe model class names within each app must also be unique, therefore theresulting name will end up being different. For example, given an app common/models.py:
  1. from django.db import models
  2.  
  3. class Base(models.Model):
  4. m2m = models.ManyToManyField(
  5. OtherModel,
  6. related_name="%(app_label)s_%(class)s_related",
  7. related_query_name="%(app_label)s_%(class)ss",
  8. )
  9.  
  10. class Meta:
  11. abstract = True
  12.  
  13. class ChildA(Base):
  14. pass
  15.  
  16. class ChildB(Base):
  17. pass

Along with another app rare/models.py:

  1. from common.models import Base
  2.  
  3. class ChildB(Base):
  4. pass

The reverse name of the common.ChildA.m2m field will becommon_childa_related and the reverse query name will be common_childas.The reverse name of the common.ChildB.m2m field will becommon_childb_related and the reverse query name will becommon_childbs. Finally, the reverse name of the rare.ChildB.m2m fieldwill be rare_childb_related and the reverse query name will berare_childbs. It's up to you how you use the '%(class)s' and'%(app_label)s' portion to construct your related name or related query namebut if you forget to use it, Django will raise errors when you perform systemchecks (or run migrate).

If you don't specify a related_nameattribute for a field in an abstract base class, the default reverse name willbe the name of the child class followed by '_set', just as it normallywould be if you'd declared the field directly on the child class. For example,in the above code, if the related_nameattribute was omitted, the reverse name for the m2m field would bechilda_set in the ChildA case and childb_set for the ChildBfield.

Multi-table inheritance

The second type of model inheritance supported by Django is when each model inthe hierarchy is a model all by itself. Each model corresponds to its owndatabase table and can be queried and created individually. The inheritancerelationship introduces links between the child model and each of its parents(via an automatically-created OneToOneField).For example:

  1. from django.db import models
  2.  
  3. class Place(models.Model):
  4. name = models.CharField(max_length=50)
  5. address = models.CharField(max_length=80)
  6.  
  7. class Restaurant(Place):
  8. serves_hot_dogs = models.BooleanField(default=False)
  9. serves_pizza = models.BooleanField(default=False)

All of the fields of Place will also be available in Restaurant,although the data will reside in a different database table. So these are bothpossible:

  1. >>> Place.objects.filter(name="Bob's Cafe")
  2. >>> Restaurant.objects.filter(name="Bob's Cafe")

If you have a Place that is also a Restaurant, you can get from thePlace object to the Restaurant object by using the lowercase version ofthe model name:

  1. >>> p = Place.objects.get(id=12)
  2. # If p is a Restaurant object, this will give the child class:
  3. >>> p.restaurant
  4. <Restaurant: ...>

However, if p in the above example was not a Restaurant (it had beencreated directly as a Place object or was the parent of some other class),referring to p.restaurant would raise a Restaurant.DoesNotExistexception.

The automatically-created OneToOneField onRestaurant that links it to Place looks like this:

  1. place_ptr = models.OneToOneField(
  2. Place, on_delete=models.CASCADE,
  3. parent_link=True,
  4. )

You can override that field by declaring your ownOneToOneField with parent_link=True on Restaurant.

Meta and multi-table inheritance

In the multi-table inheritance situation, it doesn't make sense for a childclass to inherit from its parent's Meta class. All the Meta optionshave already been applied to the parent class and applying them again wouldnormally only lead to contradictory behavior (this is in contrast with theabstract base class case, where the base class doesn't exist in its ownright).

So a child model does not have access to its parent's Meta class. However, there are a few limited cases where the childinherits behavior from the parent: if the child does not specify anordering attribute or aget_latest_by attribute, it will inheritthese from its parent.

If the parent has an ordering and you don't want the child to have any naturalordering, you can explicitly disable it:

  1. class ChildModel(ParentModel):
  2. # ...
  3. class Meta:
  4. # Remove parent's ordering effect
  5. ordering = []

Inheritance and reverse relations

Because multi-table inheritance uses an implicitOneToOneField to link the child andthe parent, it's possible to move from the parent down to the child,as in the above example. However, this uses up the name that is thedefault related_name value forForeignKey andManyToManyField relations. If youare putting those types of relations on a subclass of the parent model, youmust specify the related_nameattribute on each such field. If you forget, Django will raise a validationerror.

For example, using the above Place class again, let's create anothersubclass with a ManyToManyField:

  1. class Supplier(Place):
  2. customers = models.ManyToManyField(Place)

This results in the error:

  1. Reverse query name for 'Supplier.customers' clashes with reverse query
  2. name for 'Supplier.place_ptr'.
  3.  
  4. HINT: Add or change a related_name argument to the definition for
  5. 'Supplier.customers' or 'Supplier.place_ptr'.

Adding related_name to the customers field as follows would resolve theerror: models.ManyToManyField(Place, related_name='provider').

As mentioned, Django will automatically create aOneToOneField linking your childclass back to any non-abstract parent models. If you want to control thename of the attribute linking back to the parent, you can create yourown OneToOneField and setparent_link=Trueto indicate that your field is the link back to the parent class.

Proxy models

When using multi-table inheritance, a newdatabase table is created for each subclass of a model. This is usually thedesired behavior, since the subclass needs a place to store any additionaldata fields that are not present on the base class. Sometimes, however, youonly want to change the Python behavior of a model — perhaps to change thedefault manager, or add a new method.

This is what proxy model inheritance is for: creating a proxy for theoriginal model. You can create, delete and update instances of the proxy modeland all the data will be saved as if you were using the original (non-proxied)model. The difference is that you can change things like the default modelordering or the default manager in the proxy, without having to alter theoriginal.

Proxy models are declared like normal models. You tell Django that it's aproxy model by setting the proxy attribute ofthe Meta class to True.

For example, suppose you want to add a method to the Person model. You can do it like this:

  1. from django.db import models
  2.  
  3. class Person(models.Model):
  4. first_name = models.CharField(max_length=30)
  5. last_name = models.CharField(max_length=30)
  6.  
  7. class MyPerson(Person):
  8. class Meta:
  9. proxy = True
  10.  
  11. def do_something(self):
  12. # ...
  13. pass

The MyPerson class operates on the same database table as its parentPerson class. In particular, any new instances of Person will also beaccessible through MyPerson, and vice-versa:

  1. >>> p = Person.objects.create(first_name="foobar")
  2. >>> MyPerson.objects.get(first_name="foobar")
  3. <MyPerson: foobar>

你仍然可以使用一个代理模型来定义模型的默认排序方法。你也许不会想一直对“Persion”进行排序,但是通常情况下用代理模型根据“last_name”属性进行排序。这很简单:

  1. class OrderedPerson(Person):
  2. class Meta:
  3. ordering = ["last_name"]
  4. proxy = True

Now normal Person queries will be unorderedand OrderedPerson queries will be ordered by last_name.

代理模型继承“Meta”属性:ref:和普通模型使用同样的方法<meta-and-multi-table-inheritance>

QuerySets still return the model that was requested

There is no way to have Django return, say, a MyPerson object whenever youquery for Person objects. A queryset for Person objects will returnthose types of objects. The whole point of proxy objects is that code relyingon the original Person will use those and your own code can use theextensions you included (that no other code is relying on anyway). It is nota way to replace the Person (or any other) model everywhere with somethingof your own creation.

Base class restrictions

一个代理模型必须仅能继承一个非抽象模型类。你不能继承多个非抽象模型类,因为代理模型无法提供不同数据表的任何行间连接。一个代理模型可以继承任意数量的抽象模型类,假如他们没有定义任何的模型字段。一个代理模型也可以继承任意数量的代理模型,只需他们共享同一个非抽象父类。

代理模型管理器

If you don't specify any model managers on a proxy model, it inherits themanagers from its model parents. If you define a manager on the proxy model,it will become the default, although any managers defined on the parentclasses will still be available.

Continuing our example from above, you could change the default manager usedwhen you query the Person model like this:

  1. from django.db import models
  2.  
  3. class NewManager(models.Manager):
  4. # ...
  5. pass
  6.  
  7. class MyPerson(Person):
  8. objects = NewManager()
  9.  
  10. class Meta:
  11. proxy = True

If you wanted to add a new manager to the Proxy, without replacing theexisting default, you can use the techniques described in the custommanager documentation: create a base classcontaining the new managers and inherit that after the primary base class:

  1. # Create an abstract class for the new manager.
  2. class ExtraManagers(models.Model):
  3. secondary = NewManager()
  4.  
  5. class Meta:
  6. abstract = True
  7.  
  8. class MyPerson(Person, ExtraManagers):
  9. class Meta:
  10. proxy = True

通常情况下,你可能不需要这么做。然而,你需要的时候,这也是可以的。

Differences between proxy inheritance and unmanaged models

Proxy model inheritance might look fairly similar to creating an unmanagedmodel, using the managed attribute on amodel's Meta class.

With careful setting of Meta.db_table you could create an unmanaged model thatshadows an existing model and adds Python methods to it. However, that would bevery repetitive and fragile as you need to keep both copies synchronized if youmake any changes.

On the other hand, proxy models are intended to behave exactly like the modelthey are proxying for. They are always in sync with the parent model since theydirectly inherit its fields and managers.

The general rules are:

  • If you are mirroring an existing model or database table and don't wantall the original database table columns, use Meta.managed=False.That option is normally useful for modeling database views and tablesnot under the control of Django.
  • If you are wanting to change the Python-only behavior of a model, butkeep all the same fields as in the original, use Meta.proxy=True.This sets things up so that the proxy model is an exact copy of thestorage structure of the original model when data is saved.

Multiple inheritance

Just as with Python's subclassing, it's possible for a Django model to inheritfrom multiple parent models. Keep in mind that normal Python name resolutionrules apply. The first base class that a particular name (e.g. Meta) appears in will be the one that is used; for example, thismeans that if multiple parents contain a Meta class,only the first one is going to be used, and all others will be ignored.

Generally, you won't need to inherit from multiple parents. The main use-casewhere this is useful is for "mix-in" classes: adding a particular extrafield or method to every class that inherits the mix-in. Try to keep yourinheritance hierarchies as simple and straightforward as possible so that youwon't have to struggle to work out where a particular piece of information iscoming from.

Note that inheriting from multiple models that have a common id primarykey field will raise an error. To properly use multiple inheritance, you canuse an explicit AutoField in the base models:

  1. class Article(models.Model):
  2. article_id = models.AutoField(primary_key=True)
  3. ...
  4.  
  5. class Book(models.Model):
  6. book_id = models.AutoField(primary_key=True)
  7. ...
  8.  
  9. class BookReview(Book, Article):
  10. pass

Or use a common ancestor to hold the AutoField. Thisrequires using an explicit OneToOneField from eachparent model to the common ancestor to avoid a clash between the fields thatare automatically generated and inherited by the child:

  1. class Piece(models.Model):
  2. pass
  3.  
  4. class Article(Piece):
  5. article_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)
  6. ...
  7.  
  8. class Book(Piece):
  9. book_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)
  10. ...
  11.  
  12. class BookReview(Book, Article):
  13. pass

Field name "hiding" is not permitted

In normal Python class inheritance, it is permissible for a child class tooverride any attribute from the parent class. In Django, this isn't usuallypermitted for model fields. If a non-abstract model base class has a fieldcalled author, you can't create another model field or definean attribute called author in any class that inherits from that base class.

This restriction doesn't apply to model fields inherited from an abstractmodel. Such fields may be overridden with another field or value, or be removedby setting field_name = None.

警告

Model managers are inherited from abstract base classes. Overriding aninherited field which is referenced by an inheritedManager may cause subtle bugs. See custommanagers and model inheritance.

注解

Some fields define extra attributes on the model, e.g. aForeignKey defines an extra attribute with_id appended to the field name, as well as related_name andrelated_query_name on the foreign model.

These extra attributes cannot be overridden unless the field that definesit is changed or removed so that it no longer defines the extra attribute.

Overriding fields in a parent model leads to difficulties in areas such asinitializing new instances (specifying which field is being initialized inModel.init) and serialization. These are features which normal Pythonclass inheritance doesn't have to deal with in quite the same way, so thedifference between Django model inheritance and Python class inheritance isn'tarbitrary.

This restriction only applies to attributes which areField instances. Normal Python attributescan be overridden if you wish. It also only applies to the name of theattribute as Python sees it: if you are manually specifying the databasecolumn name, you can have the same column name appearing in both a child andan ancestor model for multi-table inheritance (they are columns in twodifferent database tables).

Django will raise a FieldError if you overrideany model field in any ancestor model.

Organizing models in a package

The manage.py startapp command creates an applicationstructure that includes a models.py file. If you have many models,organizing them in separate files may be useful.

To do so, create a models package. Remove models.py and create amyapp/models/ directory with an init.py file and the files tostore your models. You must import the models in the init.py file.

For example, if you had organic.py and synthetic.py in the modelsdirectory:

myapp/models/init.py

  1. from .organic import Person
  2. from .synthetic import Robot

Explicitly importing each model rather than using from .models import *has the advantages of not cluttering the namespace, making code more readable,and keeping code analysis tools useful.

参见

  • The Models Reference
  • Covers all the model related APIs including model fields, relatedobjects, and QuerySet.