1.多对一也可以理解为外键。比如说一个用户会写多个博客标签那用户就不能明确指定他写了哪个标签
但是标签是知道是谁写的
所以可以这样写多对一的关系
from django.contrib.auth.models import User 内置的用户表
class Category(models.Model):
name = models.CharField(max_length=32)
pub_date = models.DateTimeField('date published')
user = models.ForeignKey(User) 标签是知道谁写的所以多对一关联
slug = models.SlugField(max_length=50)
def get_absolute_url(self):
return "/blog/category/%s/" % ( self.slug)
def __unicode__(self):
return u'%s' % self.name
还有一种多对多的关联
class Entry(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published',blank=True)
content = models.TextField()
user = models.ForeignKey(User)
category = models.ForeignKey(Category)
slug = models.SlugField(
unique_for_date='pub_date',
help_text='Automatically built From the title.'
)
summary = models.TextField(help_text="One paragraph. Don't add tag.")
tags = models.ManyToManyField(Tag) 一个文章有多个标签同时一个标签也有多个文章
生成的表如下:
CREATE TABLE `blog_category` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(32) collate utf8_bin NOT NULL,
`pub_date` datetime NOT NULL,
`user_id` int(11) NOT NULL, 这个字段是生成出来的(外键关联)
`slug` varchar(50) collate utf8_bin NOT NULL,
PRIMARY KEY (`id`),
KEY `blog_category_user_id` (`user_id`),
KEY `blog_category_slug` (`slug`),
CONSTRAINT `user_id_refs_id_6c40003e` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `blog_entry` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(200) collate utf8_bin NOT NULL,
`pub_date` datetime NOT NULL,
`content` longtext collate utf8_bin NOT NULL,
`user_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`slug` varchar(50) collate utf8_bin NOT NULL,
`summary` longtext collate utf8_bin NOT NULL,
PRIMARY KEY (`id`),
KEY `blog_entry_user_id` (`user_id`),
KEY `blog_entry_category_id` (`category_id`),
KEY `blog_entry_slug` (`slug`),
CONSTRAINT `category_id_refs_id_757ac8ca` FOREIGN KEY (`category_id`) REFERENCES `blog_category` (`id`),
CONSTRAINT `user_id_refs_id_664c0c7f` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
里面有两个外键出来了
CREATE TABLE `blog_entry_tags` (
`id` int(11) NOT NULL auto_increment,
`entry_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `entry_id` (`entry_id`,`tag_id`),
KEY `tag_id_refs_id_79408990` (`tag_id`),
CONSTRAINT `tag_id_refs_id_79408990` FOREIGN KEY (`tag_id`) REFERENCES `blog_tag` (`id`),
CONSTRAINT `entry_id_refs_id_4aa52f2e` FOREIGN KEY (`entry_id`) REFERENCES `blog_entry` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
这个表就是many-many关系自动生成出来的
都是外键关联起来了!
其实发现在ORM层实现外键关联也是一个好的选择
阅读(3903) | 评论(0) | 转发(0) |