Day 73 base table / off relationship association table / cascade properties

Base table

class BaseModel(models.Model):
    
    class Meta:
        # 基表为抽象表,专门用来被继承的,提供公有字段,自身不会完成数据库迁移
        abstract = True

Off the table associated relationship

  1. It will not affect the operational efficiency even table query
  2. Will improve operational efficiency even table CRUD
  3. Easy to reconstruct the late database table
  4. Disadvantages: The database itself is not connected to the table detection, prone to dirty data, the need to avoid dirty parameter data (dirty data management when necessary) through the rigorous logic

Table Relationships

  1. Book and many Publish: foreign key in a multi-party Book
  2. And many-Book Author: foreign key in one of the high frequency queries Book
  3. Author and AuthorDetail one: To establish a foreign key in an appropriate location according to the actual needs of AuthorDetail
class Book(BaseModel):
    name = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    publish = models.Foreign(to='Publish', related_name='books', db_constraint=False, on_delete='DO_NOTHING', null=True)
    authors = models.ManyToMany(to='Author', related_name='books', db_constraint=False)

class Publish(BaseModel):
    name = models.CharField(max_length=32)
    address = models.CharField(max_length=64)
    
class Author(BaseModel):
    name = models.CharField(max_length=32)

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

Foreign key field attribute

related_name

The foreign key in the foreign key field name in the reverse lookup: Reverse to find related_name

db_constraint

The default is True indicates that the associated set False representation disassociated

on_delete

The outer key must be provided to indicate to cascade, in Django1.x, the system provides default (value models.CASCADE), under Django2.x, you must be manually clear

Cascade relations

  • CASCADE default cascade
  • DO_NOTHING foreign keys are not concatenated, it is assumed in Table A Table B dependent, record deletion B, Table A foreign key field without any treatment
  • A dependent table is assumed SET_DEFAULT Table B, B record deletion, Table A foreign key field to the value of the default attribute settings, default attribute used must meet all
  • A dependent table is assumed SET_NULL Table B, B record deletion, Table A foreign key field is set to null, all properties must be used with null = True

Note: many to many fields can not be set on_delete to cascade, cascading default, if you want to deal with a cascade relationship, you need to manually clear relational tables, foreign key handling multiple relational tables

Guess you like

Origin www.cnblogs.com/2222bai/p/12104713.html