1. 一个简单的外键用例,通过在子表声明ForeignKey可以将子表和表连接起来,其中是一对多的关系,即一个Musiccian有多个Album,一个Album只能属于一个Musician
from django.db import models class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): artist = models.ForeignKey(Musician) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField()
2.列的选项:
列的种类:model.DateField model.CharField model.IntegerField 等
附加信息:max_length例如对于CharField而言可以采用max_length来限制最大长度
default:设置默认值
primary_key=True: 设置为主键
unique=True:设置列的值必须是独一无二的
choices: 强制列的属性只能在选项之中,举例如下:
from django.db import models
class Person(models.Model):
SHIRT_SIZES = (
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
)
name = models.CharField(max_length=60)
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
through:通过一个中间关系model来建立多对多ER,举例如下
from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): # __unicode__ on Python 2 return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): # __unicode__ on Python 2 return self.name class Membership(models.Model): # 中间关系表,额外的有一些信息date_joined invite_reason,这些信息是没法在Person表和Group表体现的 person = models.ForeignKey(Person) # 并且Group没办法通过Group.members.add() create() 直接赋值来添加成员,必须通过Membership表来添加成员 group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64)
3.表之间的关系,有ForeignKey(一对多) ManyToManyField(多对多) OneToOneField(一对一)
poll = models.ForeignKey(Poll, verbose_name="the related poll") sites = models.ManyToManyField(Site, verbose_name="list of sites") place = models.OneToOneField(Place, verbose_name="related place")
4.model method 可以在model中建立方法来处理一些事
5 可以override父类的方法,例如save()方法
from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def save(self, *args, **kwargs): do_something() super(Blog, self).save(*args, **kwargs) # Call the "real" save() method. do_something_else()
6. 如何新建带外键的实例,直接将外键主表model的实例赋值给子表
blog.title = request.POST['title']
blog.author = request.user # author 为外键 request.user为实例