一、设计表

假设需求,图书管理系统:
Book: name, price, img, authors, publish, is_delete, create_time
Publish: name, address, is_delete, create_time
Author: name, age, is_delete, create_time
AuthorDetail: mobile, author, is_delete, create_time

为什么要加 is_delete 字段?

  • 只要入库的数据,永远不会被删除
  • 如果主键 id 自增时,随便删除数据,会导致 id 不连续,查询时,会遗漏数据
  • 只要该数据在入库了,就代表该数据有利用价值

为什么 Author, AuthorDetail 要拆分为两张表?

  • Author 的查询频率高,如果字段太多会影响查询效率。AuthorDetail 只在需要详情时,才会用到
  • 这两张表一般是一对一的关系

二、表关系

1.表关系设置

  • Book - Publish:多对一
    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
  • Book - Author:多对多
    authors = models.ManyToManyField(to='Author')
  • Author - AuthorDetail:一对一
    author = models.OneToOneField(to='Author', on_delete=models.CASCADE)

mark

2.断开表关联

断关联:db_constraint=True
断开关联后,可以用编程逻辑来实现表的数据同步,这样会增加效率

class Book(BaseModel):
name = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2)
img = models.ImageField(upload_to='img', default='img/default.jpg')
publish = models.ForeignKey(to='Publish', db_constraint=True, on_delete=models.CASCADE)
authors = models.ManyToManyField(to='Author')

class Meta:
db_table = 'book'
verbose_name = '书籍'
verbose_name_plural = verbose_name

def __str__(self):
class Book(BaseModel):
name = models.CharField(max_length=64)
price = models.DecimalField(max_digits=5, decimal_places=2)
img = models.ImageField(upload_to='img', default='img/default.jpg')
publish = models.ForeignKey(to='Publish', db_constraint=True, on_delete=models.CASCADE)
authors = models.ManyToManyField(to='Author')

class Meta:
db_table = 'book'
verbose_name = '书籍'
verbose_name_plural = verbose_name

def __str__(self):
return self.name

book 与 author 外键关系断开

mark

class AuthorDetail(BaseModel):
mobile = models.CharField(max_length=11)
author = models.OneToOneField(
to='Author',
db_constraint=False, # 不断开表连接
on_delete=models.CASCADE, # 删除 AuthorDetail 不会影响 Author 表,但是如果删除 Author,AuthorDetail就会被一起删除
related_name='detail' # 正向查返回 name, 反向返回设置的 related_name
)

class Meta:
db_table = 'author_detail'
verbose_name = '作者详情'
verbose_name_plural = verbose_name

def __str__(self):
return f'class AuthorDetail(BaseModel):
mobile = models.CharField(max_length=11)
author = models.OneToOneField(
to='Author',
db_constraint=False, # 不断开表连接
on_delete=models.CASCADE, # 删除 AuthorDetail 不会影响 Author 表,但是如果删除 Author,AuthorDetail就会被一起删除
related_name='detail' # 正向查返回 name, 反向返回设置的 related_name
)

class Meta:
db_table = 'author_detail'
verbose_name = '作者详情'
verbose_name_plural = verbose_name

def __str__(self):
return f'{self.author}的详情'

author 与 author_detail 表关系断开

mark

三、级联操作

1.CASCADE

  • 作者删除,详情删除:models.CASCADE
    models.py

    class AuthorDetail(BaseModel):
    mobile = models.CharField(max_length=11)
    author = models.OneToOneField(
    to='Author',
    db_constraint=False,
    related_name='detail',
    on_delete = models.CASCADE,
    )

    class Meta:
    db_table = 'author_detail'
    verbose_name = '作者详情'
    verbose_name_plural = verbose_name

    def __str__(self):
    return f'class AuthorDetail(BaseModel):
    mobile = models.CharField(max_length=11)
    author = models.OneToOneField(
    to='Author',
    db_constraint=False,
    related_name='detail',
    on_delete = models.CASCADE,
    )

    class Meta:
    db_table = 'author_detail'
    verbose_name = '作者详情'
    verbose_name_plural = verbose_name

    def __str__(self):
    return f'{self.author}的详情'

    数据库迁移

    python manage.py makemigrations
    python manage.py migrrate

    执行script.py

    import os, django

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'def_proj01.settings')
    django.setup()

    from api import models

    models.AuthorDetail.objects.filter(pk=import os, django

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'def_proj01.settings')
    django.setup()

    from api import models

    models.AuthorDetail.objects.filter(pk=1).delete()

    作者详情删除,并不会影响作者

    mark

    执行script.py

    import os, django

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'def_proj01.settings')
    django.setup()

    from api import models

    models.Author.objects.filter(pk=import os, django

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'def_proj01.settings')
    django.setup()

    from api import models

    models.Author.objects.filter(pk=1).delete()

    反之,删除作者后,详情随之删除

    mark

2.SET_NULL

  • 作者删除,外键置空: on_delete=models.SET_NULL
    models.py

    class AuthorDetail(BaseModel):
    mobile = models.CharField(max_length=11)
    author = models.OneToOneField(
    to='Author',
    db_constraint=False,
    related_name='detail',
    null=True,
    on_delete=models.SET_NULL
    )

    class Meta:
    db_table = 'author_detail'
    verbose_name = '作者详情'
    verbose_name_plural = verbose_name

    def __str__(self):
    return f'class AuthorDetail(BaseModel):
    mobile = models.CharField(max_length=11)
    author = models.OneToOneField(
    to='Author',
    db_constraint=False,
    related_name='detail',
    null=True,
    on_delete=models.SET_NULL
    )

    class Meta:
    db_table = 'author_detail'
    verbose_name = '作者详情'
    verbose_name_plural = verbose_name

    def __str__(self):
    return f'{self.author}的详情'

    数据库迁移

    python manage.py makemigrations
    python manage.py migrrate

    执行script.py

    import os, django

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'def_proj01.settings')
    django.setup()

    from api import models

    models.Author.objects.filter(pk=import os, django

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'def_proj01.settings')
    django.setup()

    from api import models

    models.Author.objects.filter(pk=1).delete()

    作者删除后,作者详情保留,但是外键置空

    mark

3.SET_DEFAULT

  • 作者删除,作者详情设置默认值: on_delete=models.SET_DEFAULT

    与 models.SET_NULL 相似,只是将空换为默认值
    models.py

    class AuthorDetail(BaseModel):
    mobile = models.CharField(max_length=11)
    author = models.OneToOneField(
    to='Author',
    db_constraint=False,
    related_name='detail',
    default='default',
    on_delete=models.SET_DEFAULT
    )

    class Meta:
    db_table = 'author_detail'
    verbose_name = '作者详情'
    verbose_name_plural = verbose_name

    def __str__(self):
    return f'class AuthorDetail(BaseModel):
    mobile = models.CharField(max_length=11)
    author = models.OneToOneField(
    to='Author',
    db_constraint=False,
    related_name='detail',
    default='default',
    on_delete=models.SET_DEFAULT
    )

    class Meta:
    db_table = 'author_detail'
    verbose_name = '作者详情'
    verbose_name_plural = verbose_name

    def __str__(self):
    return f'{self.author}的详情'

4.DO_NOTHING

  • 作者删除,作者详情不改变:on_delete=models.DO_NOTHING
    models.py

    class AuthorDetail(BaseModel):
    mobile = models.CharField(max_length=11)
    author = models.OneToOneField(
    to='Author',
    db_constraint=False,
    related_name='detail',
    default='default',
    on_delete=models.DO_NOTHING
    )

    class Meta:
    db_table = 'author_detail'
    verbose_name = '作者详情'
    verbose_name_plural = verbose_name

    def __str__(self):
    return f'class AuthorDetail(BaseModel):
    mobile = models.CharField(max_length=11)
    author = models.OneToOneField(
    to='Author',
    db_constraint=False,
    related_name='detail',
    default='default',
    on_delete=models.DO_NOTHING
    )

    class Meta:
    db_table = 'author_detail'
    verbose_name = '作者详情'
    verbose_name_plural = verbose_name

    def __str__(self):
    return f'{self.author}的详情'

四、Admin

通过 Admin 我们可以直接通过后台来编辑表

admin.py注册

from django.contrib import admin
from api from django.contrib import admin
from api import models

admin.site.register(models.Author)
admin.site.register(models.AuthorDetail)
admin.site.register(models.Book)
admin.site.register(models.Publish)

创建后台用户

manage.py@def_proj01 > createsuperuser

启动项目,登录

http://127.0.0.1:8000/admin/

mark