模型如下:
class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField()
查看生成sql用>python manage.py sqlmigrate,
生成sql:
BEGIN; --下面来解释自动生成的sql语句,生成的sql顺序比较乱,已经整理了一下 CREATE TABLE `posts_author` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `first_name` varchar(30) NOT NULL, `last_name` varchar(40) NOT NULL, `email` varchar(254) NOT NULL); -- -- -- CREATE TABLE `posts_book` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `title` varchar(100) NOT NULL, `publication_date` date NOT NULL); -- CREATE TABLE `posts_book_authors` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `book_id` integer NOT NULL, `author_id` integer NOT NULL); -- -- 这个表是没有在models中定义的,只是因为authors = models.ManyToManyField(Author) -- django就创建了一个表(多对多连接表)来处理书籍和作者之间的映射关系 --这也是数据库设计的原则,这样能较少冗余。不然的话,比如说一本书有多个作者,这个表就会重复多条数据(除了作者不同) -- CREATE TABLE `posts_publisher` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(30) NOT NULL, `address` varchar(50) NOT NULL, `city` varchar(60) NOT NULL, `state_province` varchar(30) NOT NULL, `country` varchar(50) NOT NULL, `website` varchar(200) NOT NULL); -- -- 上面分别创建的表,因为模型没有指明关键字,所以自动创建id为关键字 -- ALTER TABLE `posts_book` ADD COLUMN `publisher_id` integer NOT NULL; ALTER TABLE `posts_book` ALTER COLUMN `publisher_id` DROP DEFAULT; ALTER TABLE `posts_book` ADD CONSTRAINT `posts_book_publisher_id_4475e105_fk_posts_publisher_id` FOREIGN KEY (`publisher_id`) REFERENCES `posts_publisher` (`id`); -- -- publisher = models.ForeignKey(Publisher) -- 这句话的意思是‘参考类Publisher(也就是表posts_publisher)’ -- 创建外键,表Publisher主键是id,所以会自动加上一个字段publisher_id -- 最后就是在表posts_book 中增加外键 `posts_publisher` (`id`) -- ALTER TABLE `posts_book_authors` ADD CONSTRAINT `posts_book_authors_book_id_1487a223_fk_posts_book_id` FOREIGN KEY (`book_id`) REFERENCES `posts_book` (`id`); ALTER TABLE `posts_book_authors` ADD CONSTRAINT `posts_book_authors_author_id_0a9b3d34_fk_posts_author_id` FOREIGN KEY (`author_id`) REFERENCES `posts_author` (`id`); ALTER TABLE `posts_book_authors` ADD CONSTRAINT `posts_book_authors_book_id_7d4dbc86_uniq` UNIQUE (`book_id`, `author_id`); -- -- 这里又创建了两个外键,都是中间表‘外键’其他两个表,分别是 -- 表posts_book_authors(book_id) 外键 posts_book(id) -- 表posts_book_authors(author_id) 外键 posts_author(id) -- 最后做了唯一性约束 -- CREATE INDEX `posts_book_2604cbea` ON `posts_book` (`publisher_id`); -- --可以看出,都是表创建完成后,才进行外键设置操作 -- COMMIT;