建立具有關係的模型

多對一的關係

from django.db import models

class Author(models.Model):
   name = models.CharField(max_length=50)

#Book has a foreignkey (many to one) relationship with author
class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    publish_date = models.DateField()

最通用的選擇。可以在任何想要代表關係的地方使用

多對多關係

class Topping(models.Model):
    name = models.CharField(max_length=50)

# One pizza can have many toppings and same topping can be on many pizzas
class Pizza(models.Model):
    name = models.CharField(max_length=50)
    toppings = models.ManyToManyField(Topping)

在內部,這通過另一個表來表示。ManyToManyField 應該放在將在表單上編輯的模型上。例如:Appointment 將有一個叫 CustomerManyToManyFieldPizzaToppings 等等。

使用 Through 類的多對多關係

class Service(models.Model):
     name = models.CharField(max_length=35)

class Client(models.Model):
    name = models.CharField(max_length=35)
    age = models.IntegerField()
    services = models.ManyToManyField(Service, through='Subscription')

class Subscription(models.Model):
     client = models.ForeignKey(Client)
     service = models.ForeignKey(Service)
     subscription_type = models.CharField(max_length=1, choices=SUBSCRIPTION_TYPES)
     created_at = models.DateTimeField(default=timezone.now)

這樣,我們實際上可以保留關於兩個實體之間關係的更多後設資料。可以看出,客戶端可以通過多種訂閱型別訂閱多個服務。在這種情況下唯一的區別是,為了向 M2M 關係新增新例項,不能使用快捷方法 pizza.toppings.add(topping),而是應該建立類的新物件,Subscription.objects.create(client=client, service=service, subscription_type='p')

在其他語言中,through tables 也被稱為 JoinColumnIntersection tablemapping table

一對一的關係

class Employee(models.Model):
   name = models.CharField(max_length=50)
   age = models.IntegerField()
   spouse = models.OneToOneField(Spouse)

class Spouse(models.Model):
   name = models.CharField(max_length=50)

當你在兩個模型之間只有組合關係時,請使用這些欄位。