一、ForeignKey外键
外键是表一对多的一种写法,如下Publish表与Book属于一对多的关系,外键则需要在对应’多’的那张表下进行声明
from django.db import models
class Book(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=30)
price = models.DecimalField(max_digits=6, decimal_places=2)
pub_date = models.DateField()
publish = models.ForeignKey('Publish',to_field="id",on_delete=models.CASCADE,null=True)
author = models.ManyToManyField('Author',db_table='book2author')
class Publish(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
city = models.CharField(max_length=60)
email = models.CharField(max_length=50)
表结构如下:
book表:
publish表:
二、OneToOneField一对一
一对一关系则表示第一张表对应且唯一对应另一张表的一行数据,例如这种主要展示为人名表对应身份证信息表。声明OneToOneField可以选择两张表中的任意一张表。
class Author(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
age = models.IntegerField()
ad = models.OneToOneField('AuthorDetail',on_delete=models.CASCADE,null=True)
class AuthorDetail(models.Model):
birthday = models.DateField()
telephone = models.DateField()
addr = models.CharField(max_length=64)
表结构如下:
author表:
authordetail表:
三、ManyToManyField多对多
多对多关系则表示每一张表的一条信息都可以对应另外一种表的多条信息。orm在声明多对多的关系时会创建一个新表。
class Book(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=30)
price = models.DecimalField(max_digits=6, decimal_places=2)
pub_date = models.DateField()
publish = models.ForeignKey('Publish',to_field="id",on_delete=models.CASCADE,null=True)
author = models.ManyToManyField('Author',db_table='book2author')
class Author(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
age = models.IntegerField()
ad = models.OneToOneField('AuthorDetail',on_delete=models.CASCADE,null=True)
表结构如下:
book2author表:
留言