您的位置:首页 > 编程语言 > Go语言

django 多对多关系的操作 包含映射表

2014-02-13 11:42 561 查看
图书馆的书,借书的学生为多对多关系

分为三张表,book ,stduent ,book_relation映射表

class Book:
name = models.CharField(max_length=100)
relation =models.ManyToManyField(student)

class Student(models.Model):
sname = models.CharField(max_length=100)


在自动生成数据库表的时候,会生成book表,student表,book_relation表,映射表名字的生成规则为models中class Book的名字加上manytomany的名字,即book+relation

插入数据

如果需要增加学生信息则student = Student(sname='1')

否则student = Student.objects.get(id=1)

book.relation.add(student)

book.save()

删除数据

student = Student.objects.get(id=1)

book.relation.remove(student)

book.save()

class Student(models.Model):
name = models.CharField(max_length=5)
cources = models.ManyToManyField(Course, through='StudentCourse')
class Course(models.Model):
name = models.CharField()
class StudentCourse(models.Model):
student = models.ForeignKey(Student)
course = models.ForeignKey(Course)
score=models.FloatField()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: