模型是您的数据唯一而且准确的信息来源。它包含您正在储存的数据的重要字段和行为。一般来说,每一个模型都映射一个数据库表。
基础:
django.db.models.Model
这个样例模型定义了一个 Person
, 其拥有 first_name
和 last_name
:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
first_name
和 last_name
是模型的字段。每个字段都被指定为一个类属性,并且每个属性映射为一个数据库列。
上面的 Person
模型会创建一个如下的数据库表:
CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);
一些技术上的说明:
id
字段会被自动添加,但是这种行为可以被改写。请参阅:默认主键字段。CREATE TABLE
SQL in this example is formatted using PostgreSQL
syntax, but it's worth noting Django uses SQL tailored to the database
backend specified in your settings file.一旦你定义了你的模型,你需要告诉 Django 你准备*使用*这些模型。你需要修改设置文件中的 INSTALLED_APPS
,在这个设置中添加包含你 models.py
文件的模块的名字。
例如,如果模型位于你项目中的``myapp.models``中( 此包结构使用:djadmin:manage.py startapp`命令创建),:setting:`INSTALLED_APPS 应设置如下:
INSTALLED_APPS = [
#...
'myapp',
#...
]
When you add new apps to INSTALLED_APPS
, be sure to run
manage.py migrate
, optionally making migrations
for them first with manage.py makemigrations
.
模型中最重要的、并且也是唯一必须的是数据库的字段定义。字段在类中定义。定义字段名时应小心避免使用与 models API</ref/models/instances>冲突的名称, 如 ``clean`, save
, or ``delete``等.
举例:
from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
模型中每一个字段都应该是相应类的实例, Django 利用这些字段类来实现下面这些功能。
INTEGER
, VARCHAR
, TEXT
)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
该参数接收一个可迭代的列表或元组(基本单位为二元组)。如果指定了该参数,在实例化该模型时,该字段只能取选项列表中的值。
一个选项列表:
YEAR_IN_SCHOOL_CHOICES = (
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
('GR', 'Graduate'),
)
每个二元组的第一个值会储存在数据库中,而第二个值将只会用于显示作用。
对于一个模型实例,要获取该字段二元组中相对应的第二个值,使用 get_FOO_display()
方法。例如:
from django.db import models
class Person(models.Model):
SHIRT_SIZES = (
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
)
name = models.CharField(max_length=60)
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
>>> p = Person(name="Fred Flintstone", shirt_size="L")
>>> p.save()
>>> p.shirt_size
'L'
>>> p.get_shirt_size_display()
'Large'
default
help_text
primary_key
如果设置为 True
,将该字段设置为该模型的主键。
在一个模型中,如果你没有对任何一个字段设置 primary_key=True
选项。 Django 会自动添加一个 IntegerField
字段,用于设置为主键,因此除非你想重写 Django 默认的主键设置行为,你可以不手动设置主键。详情请见 自动设置主键 。
主键字段是只可读的,如果你修改一个模型实例该字段的值并保存,你将等同于创建了一个新的模型实例。例如:
from django.db import models
class Fruit(models.Model):
name = models.CharField(max_length=100, primary_key=True)
>>> fruit = Fruit.objects.create(name='Apple')
>>> fruit.name = 'Pear'
>>> fruit.save()
>>> Fruit.objects.values_list('name', flat=True)
<QuerySet ['Apple', 'Pear']>
unique
True
, this field must be unique throughout the table.再次声明,以上只是一些通用参数的简略描述。你可以在 :ref:`common model field option reference<common-model-field-options> ` 中找到完整的介绍。
默认情况下, Django 会给每一个模型添加下面的字段:
id = models.AutoField(primary_key=True)
这是一个自增的主键。
如果你想指定设置为为主键的字段, 在你想要设置为主键的字段上设置 primary_key=True
选项。如果 Django 看到你显式的设置了 Field.primary_key
,将不会自动在表(模型)中添加 id
列。
每个模型都需要拥有一个设置了 primary_key=True
的字段(无论是显式的设置还是 Django 自动设置)。
除了 ForeignKey
, ManyToManyField
和 OneToOneField
,任何字段类型都接收一个可选的参数 verbose_name
,如果未指定该参数值, Django 会自动使用该字段的属性名作为该参数值,并且把下划线转换为空格。
在该例中:备注名为 "person's first name"
:: 。
first_name = models.CharField("person's first name", max_length=30)
在该例中:备注名为 "first name"
:: 。
first_name = models.CharField(max_length=30)
ForeignKey
, ManyToManyField
and OneToOneField
接收的第一个参数为模型的类名,后面可以添加一个 verbose_name
参数:
poll = models.ForeignKey(
Poll,
on_delete=models.CASCADE,
verbose_name="the related poll",
)
sites = models.ManyToManyField(Site, verbose_name="list of sites")
place = models.OneToOneField(
Place,
on_delete=models.CASCADE,
verbose_name="related place",
)
一般情况下不需要将 verbose_name
值首字母大写,必要时 Djanog 会自动把首字母转换为大写。
显然,关系型数据库的强大之处在于各表之间的关联关系。 Django 提供了定义三种最常见的数据库关联关系的方法:多对一,多对多,一对一。
定义一个多对一的关联关系,使用 django.db.models.ForeignKey
类。就和其他 Field
字段类型一样,只需要在你模型中添加一个值为该类的属性。
ForeignKey
requires a positional argument: the class
to which the model is related.
例如,如果一个 Car
模型 有一个制造者 Manufacturer
--就是说一个 Manufacturer
制造许多辆车,但是每辆车都属于某个特定的制造者-- 那么使用下面的方法定义这个关系:
from django.db import models
class Manufacturer(models.Model):
# ...
pass
class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
# ...
你也可以创建一个 recursive relationships 关系(一个模型与它本身有多对一的关系)和 :ref:`relationships to models not yet defined <lazy-relationships> ` ;详情请见 :ref:`the model field reference <ref-foreignkey> ` 。
建议设置 ForeignKey
字段(上例中的 manufacturer
)名为想要关联的模型名,但是你也可以随意设置为你想要的名称,例如:
class Car(models.Model):
company_that_makes_it = models.ForeignKey(
Manufacturer,
on_delete=models.CASCADE,
)
# ...
参见
ForeignKey
字段还可以接收一些其他的参数,详见 the model field reference ,这些可选的参数可以更深入的规定光联关系的具体实现。
For details on accessing backwards-related objects, see the Following relationships backward example.
如要查看相关示例代码,详见 :doc:`Many-to-one relationship model example </topics/db/examples/many_to_one> ` 。
定义一个多对多的关联关系,使用 django.db.models.ManyToManyField
类。就和其他 Field
字段类型一样,只需要在你模型中添加一个值为该类的属性。
ManyToManyField
requires a positional argument: the
class to which the model is related.
例如:如果 Pizza
含有多种 Topping``(配料) -- 也就是一种 ``Topping
可能存在于多个 Pizza
中,并且每个 Pizza
含有多种 Topping
--那么可以这样表示这种关系:
from django.db import models
class Topping(models.Model):
# ...
pass
class Pizza(models.Model):
# ...
toppings = models.ManyToManyField(Topping)
和 ForeignKey
类一样,你也可以创建 recursive relationships 关系(一个对象与他本身有着多对多的关系)和 relationships to models not yet defined 关系。
建议设置 ManyToManyField
字段(上例中的 toppings
)名为一个复数名词,表示所要光联的模型对象的集合。
对于多对多光联关系的两个模型,可以在任何一个模型中添加 ManyToManyField
字段,但只能选择一个模型设置该字段,即不能同时在两模型中添加该字段。
Generally, ManyToManyField
instances should go in
the object that's going to be edited on a form. In the above example,
toppings
is in Pizza
(rather than Topping
having a pizzas
ManyToManyField
) because it's more natural to think
about a pizza having toppings than a topping being on multiple pizzas. The way
it's set up above, the Pizza
form would let users select the toppings.
参见
如要查看完整示例代码,详见 Many-to-many relationship model example。
ManyToManyField
fields also accept a number of
extra arguments which are explained in the model field reference. These options help define how the relationship
should work; all are optional.
When you're only dealing with simple many-to-many relationships such as
mixing and matching pizzas and toppings, a standard
ManyToManyField
is all you need. However, sometimes
you may need to associate data with the relationship between two models.
For example, consider the case of an application tracking the musical groups
which musicians belong to. There is a many-to-many relationship between a person
and the groups of which they are a member, so you could use a
ManyToManyField
to represent this relationship.
However, there is a lot of detail about the membership that you might want to
collect, such as the date at which the person joined the group.
For these situations, Django allows you to specify the model that will be used
to govern the many-to-many relationship. You can then put extra fields on the
intermediate model. The intermediate model is associated with the
ManyToManyField
using the
through
argument to point to the model
that will act as an intermediary. For our musician example, the code would look
something like this:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
When you set up the intermediary model, you explicitly specify foreign keys to the models that are involved in the many-to-many relationship. This explicit declaration defines how the two models are related.
There are a few restrictions on the intermediate model:
Group
in our example), or you must
explicitly specify the foreign keys Django should use for the relationship
using ManyToManyField.through_fields
.
If you have more than one foreign key and through_fields
is not
specified, a validation error will be raised. A similar restriction applies
to the foreign key to the target model (this would be Person
in our
example).through_fields
as above, or a validation error
will be raised.symmetrical=False
(see
the model field reference).Now that you have set up your ManyToManyField
to use
your intermediary model (Membership
, in this case), you're ready to start
creating some many-to-many relationships. You do this by creating instances of
the intermediate model:
>>> ringo = Person.objects.create(name="Ringo Starr")
>>> paul = Person.objects.create(name="Paul McCartney")
>>> beatles = Group.objects.create(name="The Beatles")
>>> m1 = Membership(person=ringo, group=beatles,
... date_joined=date(1962, 8, 16),
... invite_reason="Needed a new drummer.")
>>> m1.save()
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>]>
>>> ringo.group_set.all()
<QuerySet [<Group: The Beatles>]>
>>> m2 = Membership.objects.create(person=paul, group=beatles,
... date_joined=date(1960, 8, 1),
... invite_reason="Wanted to form a band.")
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>]>
Unlike normal many-to-many fields, you can't use add()
, create()
,
or set()
to create relationships:
>>> # The following statements will not work
>>> beatles.members.add(john)
>>> beatles.members.create(name="George Harrison")
>>> beatles.members.set([john, paul, ringo, george])
Why? You can't just create a relationship between a Person
and a Group
- you need to specify all the detail for the relationship required by the
Membership
model. The simple add
, create
and assignment calls
don't provide a way to specify this extra detail. As a result, they are
disabled for many-to-many relationships that use an intermediate model.
The only way to create this type of relationship is to create instances of the
intermediate model.
The remove()
method is
disabled for similar reasons. For example, if the custom through table defined
by the intermediate model does not enforce uniqueness on the
(model1, model2)
pair, a remove()
call would not provide enough
information as to which intermediate model instance should be deleted:
>>> Membership.objects.create(person=ringo, group=beatles,
... date_joined=date(1968, 9, 4),
... invite_reason="You've been gone for a month and we miss you.")
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>, <Person: Ringo Starr>]>
>>> # This will not work because it cannot tell which membership to remove
>>> beatles.members.remove(ringo)
However, the clear()
method can be used to remove all many-to-many relationships for an instance:
>>> # Beatles have broken up
>>> beatles.members.clear()
>>> # Note that this deletes the intermediate model instances
>>> Membership.objects.all()
<QuerySet []>
Once you have established the many-to-many relationships by creating instances of your intermediate model, you can issue queries. Just as with normal many-to-many relationships, you can query using the attributes of the many-to-many-related model:
# Find all the groups with a member whose name starts with 'Paul'
>>> Group.objects.filter(members__name__startswith='Paul')
<QuerySet [<Group: The Beatles>]>
As you are using an intermediate model, you can also query on its attributes:
# Find all the members of the Beatles that joined after 1 Jan 1961
>>> Person.objects.filter(
... group__name='The Beatles',
... membership__date_joined__gt=date(1961,1,1))
<QuerySet [<Person: Ringo Starr]>
If you need to access a membership's information you may do so by directly
querying the Membership
model:
>>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
>>> ringos_membership.date_joined
datetime.date(1962, 8, 16)
>>> ringos_membership.invite_reason
'Needed a new drummer.'
Another way to access the same information is by querying the
many-to-many reverse relationship from a
Person
object:
>>> ringos_membership = ringo.membership_set.get(group=beatles)
>>> ringos_membership.date_joined
datetime.date(1962, 8, 16)
>>> ringos_membership.invite_reason
'Needed a new drummer.'
To define a one-to-one relationship, use
OneToOneField
. You use it just like any other
Field
type: by including it as a class attribute of your model.
This is most useful on the primary key of an object when that object "extends" another object in some way.
OneToOneField
requires a positional argument: the
class to which the model is related.
For example, if you were building a database of "places", you would
build pretty standard stuff such as address, phone number, etc. in the
database. Then, if you wanted to build a database of restaurants on
top of the places, instead of repeating yourself and replicating those
fields in the Restaurant
model, you could make Restaurant
have
a OneToOneField
to Place
(because a
restaurant "is a" place; in fact, to handle this you'd typically use
inheritance, which involves an implicit
one-to-one relation).
As with ForeignKey
, a recursive relationship can be defined and references to as-yet
undefined models can be made.
参见
See the One-to-one relationship model example for a full example.
OneToOneField
fields also accept an optional
parent_link
argument.
OneToOneField
classes used to automatically become
the primary key on a model. This is no longer true (although you can manually
pass in the primary_key
argument if you like).
Thus, it's now possible to have multiple fields of type
OneToOneField
on a single model.
It's perfectly OK to relate a model to one from another app. To do this, import the related model at the top of the file where your model is defined. Then, just refer to the other model class wherever needed. For example:
from django.db import models
from geography.models import ZipCode
class Restaurant(models.Model):
# ...
zip_code = models.ForeignKey(
ZipCode,
on_delete=models.SET_NULL,
blank=True,
null=True,
)
Django places only two restrictions on model field names:
A field name cannot be a Python reserved word, because that would result in a Python syntax error. For example:
class Example(models.Model):
pass = models.IntegerField() # 'pass' is a reserved word!
A field name cannot contain more than one underscore in a row, due to the way Django's query lookup syntax works. For example:
class Example(models.Model):
foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
These limitations can be worked around, though, because your field name doesn't
necessarily have to match your database column name. See the
db_column
option.
SQL reserved words, such as join
, where
or select
, are allowed as
model field names, because Django escapes all database table names and column
names in every underlying SQL query. It uses the quoting syntax of your
particular database engine.
If one of the existing model fields cannot be used to fit your purposes, or if you wish to take advantage of some less common database column types, you can create your own field class. Full coverage of creating your own fields is provided in 编写自定义 model fields.
Meta
options¶Give your model metadata by using an inner class Meta
, like so:
from django.db import models
class Ox(models.Model):
horn_length = models.IntegerField()
class Meta:
ordering = ["horn_length"]
verbose_name_plural = "oxen"
Model metadata is "anything that's not a field", such as ordering options
(ordering
), database table name (db_table
), or
human-readable singular and plural names (verbose_name
and
verbose_name_plural
). None are required, and adding class
Meta
to a model is completely optional.
A complete list of all possible Meta
options can be found in the model
option reference.
objects
Manager
. It's the interface through which
database query operations are provided to Django models and is used to
retrieve the instances from the database. If no
custom Manager
is defined, the default name is
objects
. Managers are only accessible via
model classes, not the model instances.Define custom methods on a model to add custom "row-level" functionality to your
objects. 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 -- the model.
For example, this model has a few custom methods:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField()
def baby_boomer_status(self):
"Returns the person's baby-boomer status."
import datetime
if self.birth_date < datetime.date(1945, 8, 1):
return "Pre-boomer"
elif self.birth_date < datetime.date(1965, 1, 1):
return "Baby boomer"
else:
return "Post-boomer"
@property
def full_name(self):
"Returns the person's full name."
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 list of 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 any object. This is what Python and Django will use whenever a model instance needs to be coerced and displayed as a plain string. Most notably, this happens when you display an object in an interactive console or in the admin.
You'll always want to define this method; the default isn't very helpful at all.
get_absolute_url()
This tells Django how to calculate the URL for an object. Django uses this in its admin interface, and any time it needs to figure out a URL for an object.
Any object that has a URL that uniquely identifies it should define this method.
There's another set of model methods that
encapsulate a bunch of database behavior that you'll want to customize. In
particular you'll often want to change the way save()
and
delete()
work.
You're free to override these methods (and any other model method) to alter behavior.
A classic use-case for overriding the built-in methods is if you want something
to happen whenever you save an object. For example (see
save()
for documentation of the parameters it accepts):
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def save(self, *args, **kwargs):
do_something()
super().save(*args, **kwargs) # Call the "real" save() method.
do_something_else()
You can also prevent saving:
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def save(self, *args, **kwargs):
if self.name == "Yoko Ono's blog":
return # Yoko shall never have her own blog!
else:
super().save(*args, **kwargs) # Call the "real" save() method.
It's important to remember to call the superclass method -- that's
that super().save(*args, **kwargs)
business -- to ensure
that the object still gets saved into the database. If you forget to
call the superclass method, the default behavior won't happen and the
database won't get touched.
It's also important that you pass through the arguments that can be
passed to the model method -- that's what the *args, **kwargs
bit
does. Django will, from time to time, extend the capabilities of
built-in model methods, adding new arguments. If you use *args,
**kwargs
in your method definitions, you are guaranteed that your
code 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 not
necessarily called when deleting objects in bulk using a
QuerySet or as a result of a cascading
delete
. To ensure customized
delete logic gets executed, you can use
pre_delete
and/or
post_delete
signals.
Unfortunately, there isn't a workaround when
creating
or
updating
objects in bulk,
since none of save()
,
pre_save
, and
post_save
are called.
Another common pattern is writing custom SQL statements in model methods and module-level methods. For more details on using raw SQL, see the documentation on using raw SQL.
模型继承在 Django 中与普通类继承在 Python 中的工作方式几乎完全相同, 但也仍应遵循本页开头的内容. 这意味着其基类应该继承自 django.db.models.Model
.
The only decision you have to make is whether you want the parent models to be models in their own right (with their own database tables), or if the parents are just holders of common information that will only be visible through the child models.
There are three styles of inheritance that are possible in Django.
Abstract base classes are useful when you want to put some common
information into a number of other models. You write your base class
and put abstract=True
in the Meta
class. This model will then not be used to create any database
table. Instead, when it is used as a base class for other models, its
fields will be added to those of the child class.
An example:
from django.db import models
class CommonInfo(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
class Meta:
abstract = True
class Student(CommonInfo):
home_group = models.CharField(max_length=5)
The Student
model will have three fields: name
, age
and
home_group
. The CommonInfo
model cannot be used as a normal Django
model, since it is an abstract base class. It does not generate a database
table or have a manager, and cannot be instantiated or saved directly.
Fields inherited from abstract base classes can be overridden with another
field 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, while still only creating one database table per child model at the database level.
Meta
inheritance¶When an abstract base class is created, Django makes any Meta inner class you declared in the base class available as an attribute. If a child class does not declare its own Meta class, it will inherit the parent's Meta. If the child wants to extend the parent's Meta class, it can subclass it. For example:
from django.db import models
class CommonInfo(models.Model):
# ...
class Meta:
abstract = True
ordering = ['name']
class Student(CommonInfo):
# ...
class Meta(CommonInfo.Meta):
db_table = 'student_info'
Django does make one adjustment to the Meta class of an abstract base
class: before installing the Meta attribute, it sets abstract=False
.
This means that children of abstract base classes don't automatically become
abstract classes themselves. Of course, you can make an abstract base class
that inherits from another abstract base class. You just need to remember to
explicitly set abstract=True
each time.
Some attributes won't make sense to include in the Meta class of an
abstract base class. For example, including db_table
would mean that all
the child classes (the ones that don't specify their own Meta) would use
the same database table, which is almost certainly not what you want.
The second type of model inheritance supported by Django is when each model in
the hierarchy is a model all by itself. Each model corresponds to its own
database table and can be queried and created individually. The inheritance
relationship introduces links between the child model and each of its parents
(via an automatically-created OneToOneField
).
For example:
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
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 both
possible:
>>> Place.objects.filter(name="Bob's Cafe")
>>> Restaurant.objects.filter(name="Bob's Cafe")
If you have a Place
that is also a Restaurant
, you can get from the
Place
object to the Restaurant
object by using the lower-case version
of the model name:
>>> p = Place.objects.get(id=12)
# If p is a Restaurant object, this will give the child class:
>>> p.restaurant
<Restaurant: ...>
However, if p
in the above example was not a Restaurant
(it had been
created directly as a Place
object or was the parent of some other class),
referring to p.restaurant
would raise a Restaurant.DoesNotExist
exception.
The automatically-created OneToOneField
on
Restaurant
that links it to Place
looks like this:
place_ptr = models.OneToOneField(
Place, on_delete=models.CASCADE,
parent_link=True,
)
You can override that field by declaring your own
OneToOneField
with parent_link=True
on Restaurant
.
Meta
and multi-table inheritance¶In the multi-table inheritance situation, it doesn't make sense for a child class to inherit from its parent's Meta class. All the Meta options have already been applied to the parent class and applying them again would normally only lead to contradictory behavior (this is in contrast with the abstract base class case, where the base class doesn't exist in its own right).
So a child model does not have access to its parent's Meta class. However, there are a few limited cases where the child
inherits behavior from the parent: if the child does not specify an
ordering
attribute or a
get_latest_by
attribute, it will inherit
these from its parent.
If the parent has an ordering and you don't want the child to have any natural ordering, you can explicitly disable it:
class ChildModel(ParentModel):
# ...
class Meta:
# Remove parent's ordering effect
ordering = []
Because multi-table inheritance uses an implicit
OneToOneField
to link the child and
the 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 the
default related_name
value for
ForeignKey
and
ManyToManyField
relations. If you
are putting those types of relations on a subclass of the parent model, you
must specify the related_name
attribute on each such field. If you forget, Django will raise a validation
error.
For example, using the above Place
class again, let's create another
subclass with a ManyToManyField
:
class Supplier(Place):
customers = models.ManyToManyField(Place)
This results in the error:
Reverse query name for 'Supplier.customers' clashes with reverse query
name for 'Supplier.place_ptr'.
HINT: Add or change a related_name argument to the definition for
'Supplier.customers' or 'Supplier.place_ptr'.
Adding related_name
to the customers
field as follows would resolve the
error: models.ManyToManyField(Place, related_name='provider')
.
As mentioned, Django will automatically create a
OneToOneField
linking your child
class back to any non-abstract parent models. If you want to control the
name of the attribute linking back to the parent, you can create your
own OneToOneField
and set
parent_link=True
to indicate that your field is the link back to the parent class.
When using multi-table inheritance, a new database table is created for each subclass of a model. This is usually the desired behavior, since the subclass needs a place to store any additional data fields that are not present on the base class. Sometimes, however, you only want to change the Python behavior of a model -- perhaps to change the default manager, or add a new method.
This is what proxy model inheritance is for: creating a proxy for the original model. You can create, delete and update instances of the proxy model and 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 model ordering or the default manager in the proxy, without having to alter the original.
Proxy models are declared like normal models. You tell Django that it's a
proxy model by setting the proxy
attribute of
the Meta
class to True
.
For example, suppose you want to add a method to the Person
model. You can do it like this:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class MyPerson(Person):
class Meta:
proxy = True
def do_something(self):
# ...
pass
The MyPerson
class operates on the same database table as its parent
Person
class. In particular, any new instances of Person
will also be
accessible through MyPerson
, and vice-versa:
>>> p = Person.objects.create(first_name="foobar")
>>> MyPerson.objects.get(first_name="foobar")
<MyPerson: foobar>
你仍然可以使用一个代理模型来定义模型的默认排序方法。你也许不会想一直对“Persion”进行排序,但是通常情况下用代理模型根据“last_name”属性进行排序。这很简单:
class OrderedPerson(Person):
class Meta:
ordering = ["last_name"]
proxy = True
Now normal Person
queries will be unordered
and OrderedPerson
queries will be ordered by last_name
.
代理模型继承“Meta”属性:ref:和普通模型使用同样的方法<meta-and-multi-table-inheritance>。
QuerySet
s still return the model that was requested¶There is no way to have Django return, say, a MyPerson
object whenever you
query for Person
objects. A queryset for Person
objects will return
those types of objects. The whole point of proxy objects is that code relying
on the original Person
will use those and your own code can use the
extensions you included (that no other code is relying on anyway). It is not
a way to replace the Person
(or any other) model everywhere with something
of your own creation.
一个代理模型必须仅能继承一个非抽象模型类。你不能继承多个非抽象模型类,因为代理模型无法提供不同数据表的任何行间连接。一个代理模型可以继承任意数量的抽象模型类,假如他们*没有*定义任何的模型字段。一个代理模型也可以继承任意数量的代理模型,只需他们共享同一个非抽象父类。
If you don't specify any model managers on a proxy model, it inherits the managers from its model parents. If you define a manager on the proxy model, it will become the default, although any managers defined on the parent classes will still be available.
Continuing our example from above, you could change the default manager used
when you query the Person
model like this:
from django.db import models
class NewManager(models.Manager):
# ...
pass
class MyPerson(Person):
objects = NewManager()
class Meta:
proxy = True
If you wanted to add a new manager to the Proxy, without replacing the existing default, you can use the techniques described in the custom manager documentation: create a base class containing the new managers and inherit that after the primary base class:
# Create an abstract class for the new manager.
class ExtraManagers(models.Model):
secondary = NewManager()
class Meta:
abstract = True
class MyPerson(Person, ExtraManagers):
class Meta:
proxy = True
通常情况下,你可能不需要这么做。然而,你需要的时候,这也是可以的。
Proxy model inheritance might look fairly similar to creating an unmanaged
model, using the managed
attribute on a
model's Meta
class.
With careful setting of Meta.db_table
you could create an unmanaged model that
shadows an existing model and adds Python methods to it. However, that would be
very repetitive and fragile as you need to keep both copies synchronized if you
make any changes.
On the other hand, proxy models are intended to behave exactly like the model they are proxying for. They are always in sync with the parent model since they directly inherit its fields and managers.
The general rules are:
Meta.managed=False
.
That option is normally useful for modeling database views and tables
not under the control of Django.Meta.proxy=True
.
This sets things up so that the proxy model is an exact copy of the
storage structure of the original model when data is saved.Just as with Python's subclassing, it's possible for a Django model to inherit from multiple parent models. Keep in mind that normal Python name resolution rules apply. The first base class that a particular name (e.g. Meta) appears in will be the one that is used; for example, this means 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-case where this is useful is for "mix-in" classes: adding a particular extra field or method to every class that inherits the mix-in. Try to keep your inheritance hierarchies as simple and straightforward as possible so that you won't have to struggle to work out where a particular piece of information is coming from.
Note that inheriting from multiple models that have a common id
primary
key field will raise an error. To properly use multiple inheritance, you can
use an explicit AutoField
in the base models:
class Article(models.Model):
article_id = models.AutoField(primary_key=True)
...
class Book(models.Model):
book_id = models.AutoField(primary_key=True)
...
class BookReview(Book, Article):
pass
Or use a common ancestor to hold the AutoField
. This
requires using an explicit OneToOneField
from each
parent model to the common ancestor to avoid a clash between the fields that
are automatically generated and inherited by the child:
class Piece(models.Model):
pass
class Article(Piece):
article_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)
...
class Book(Piece):
book_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)
...
class BookReview(Book, Article):
pass
In normal Python class inheritance, it is permissible for a child class to
override any attribute from the parent class. In Django, this isn't usually
permitted for model fields. If a non-abstract model base class has a field
called author
, you can't create another model field or define
an attribute called author
in any class that inherits from that base class.
This restriction doesn't apply to model fields inherited from an abstract
model. Such fields may be overridden with another field or value, or be removed
by setting field_name = None
.
警告
Model managers are inherited from abstract base classes. Overriding an
inherited field which is referenced by an inherited
Manager
may cause subtle bugs. See custom
managers and model inheritance.
注解
Some fields define extra attributes on the model, e.g. a
ForeignKey
defines an extra attribute with
_id
appended to the field name, as well as related_name
and
related_query_name
on the foreign model.
These extra attributes cannot be overridden unless the field that defines it 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 as
initializing new instances (specifying which field is being initialized in
Model.__init__
) and serialization. These are features which normal Python
class inheritance doesn't have to deal with in quite the same way, so the
difference between Django model inheritance and Python class inheritance isn't
arbitrary.
This restriction only applies to attributes which are
Field
instances. Normal Python attributes
can be overridden if you wish. It also only applies to the name of the
attribute as Python sees it: if you are manually specifying the database
column name, you can have the same column name appearing in both a child and
an ancestor model for multi-table inheritance (they are columns in two
different database tables).
Django will raise a FieldError
if you override
any model field in any ancestor model.
The manage.py startapp
command creates an application
structure 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 a
myapp/models/
directory with an __init__.py
file and the files to
store your models. You must import the models in the __init__.py
file.
For example, if you had organic.py
and synthetic.py
in the models
directory:
from .organic import Person
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.
参见
QuerySet
.1月 11, 2019