mysql 外键

  1. sql新建
CREATE DATABASE IF NOT EXISTS dbdemo;

USE dbdemo;

CREATE TABLE categories(
   cat_id int not null auto_increment primary key,
   cat_name varchar(255) not null,
   cat_description text
) ENGINE=InnoDB;

CREATE TABLE products(
   prd_id int not null auto_increment primary key,
   prd_name varchar(355) not null,
   prd_price decimal,
   cat_id int not null,
   FOREIGN KEY fk_cat(cat_id)
   REFERENCES categories(cat_id)
   ON UPDATE CASCADE
   ON DELETE RESTRICT
)ENGINE=InnoDB;


  1. sql修改
USE dbdemo;

CREATE TABLE vendors(
    vdr_id int not null auto_increment primary key,
    vdr_name varchar(255)
)ENGINE=InnoDB;


ALTER TABLE products 
ADD COLUMN vdr_id int not null AFTER cat_id;


ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

  1. ORM新建
class UserGroup(models.Model):
    uid = models.Auto(primary_key=True)
    title=models.CharField(max_length=32,unique=True)

class UserInfo(models.Model):
    username=models.CharField(max_length=32)
    user_group = models.ForeignKey("UserGroup", to_field="uid", default=1, on_delete=models.CASCADE)


原文地址:https://www.cnblogs.com/amize/p/14102653.html