django-1.11英文文档笔记-model关系映射

博客介绍了Django中定义数据库三种常见关系的方法。使用ForeignKey定义多对一关系,ManyToManyField定义多对多关系,OneToOneField定义一对一关系。其中,多对多关系还可通过中间表处理复杂情况,各方法都需指定关联的model class。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Clearly, the power of relational databases lies in relating tables to each other. Django offers ways to define the three most common types of database relationships: many-to-one, many-to-many and one-to-one.

1、Many-to-one relationships

To define a many-to-one relationship, use django.db.models.ForeignKey. You use it just like any other Field type: by including it as a class attribute of your model.
ForeignKey requires a positional argument: the class to which the model is related.
For example, if a Car model has a Manufacturer – that is, a Manufacturer makes multiple cars but each Car
only has one Manufacturer – use the following definitions:

from django.db import models
class Manufacturer(models.Model): # ...
    pass
class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) # ...
  • 在django中,使用 ForeignKey 来表示关系数据库中的多对-关系(many-to-one)。
  • ForeignKey 方法有个必须的位置参数,就是相关联的model的 class。
  • 上述代码就是多对一关系例子的写法:Car 只能有一个 Manufacturer, 而 Manufacturer 可以制造多个 Car。所以在配置 Car 类时, 多了一个 ForeignKey。

2、Many-to-many relationships

To define a many-to-many relationship, use ManyToManyField. You use it just like any other Field type: by including it as a class attribute of your model.
ManyToManyField requires a positional argument: the class to which the model is related.
For example, if a Pizza has multiple Topping objects – that is, a Topping can be on multiple pizzas and each
Pizza has multiple toppings – here’s how you’d represent that:

from django.db import models
class Topping(models.Model): # ...
    pass
class Pizza(models.Model): # ...
    toppings = models.ManyToManyField(Topping)

It doesn’t matter which model has the ManyToManyField, but you should only put it in one of the models – not both.
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.

  • 在django中,使用 ManyToManyField 来表示多对多关系(many-to-many)。
  • ManyToManyField 方法有个必须的位置参数:相关联的model class。
  • ManyToManyField 可以在相关联的任何一方进行定义,但不能两边都定义。
  • 通常,ManyToManyField 定义在需要在表单中编辑的那一方。例如,Pizza(披萨) 和 Toppings(配料),ManyToManyField 会定义在 Pizza 中。

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 rela- tionship. 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): # __unicode__ on Python 2
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')
    def __str__(self): # __unicode__ on Python 2 
        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.

  • django对于处理复杂的多对多关系时,还提供了一种 中间表(intermediary model) 的解决方案。
  • page 90

3、One-to-one relationships

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.

  • 在django中使用 OneToOneField 来定义一对一关系映射(one-to-one)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值