美文网首页
Django-18-多对多

Django-18-多对多

作者: 西海岸虎皮猫大人 | 来源:发表于2020-04-08 16:13 被阅读0次

    模型

    # 课程表 和 教师表 n:n
    class Course(models.Model):
        course_id=models.AutoField(primary_key=True)
        course_name=models.CharField(max_length=30,unique=True)
    
        class Meta:
            db_table='t_course'
    
        def __unicode__(self):
            return u'Course:%s'%self.course_name
    
    class Teacher(models.Model):
        tid = models.AutoField(primary_key=True)
        tname = models.CharField(max_length=30,unique=True)
        course = models.ManyToManyField(Course)
    
        class Meta:
            db_table='t_teacher'
    
        def __unicode__(self):
            return u'Teacher:%s--%s'%(self.tname,self.course)
    

    迁移时会创建一张关联表

    插入数据

    from stu.models import *
    cou1 = Course(course_name='Java')
    cou2 = Course(course_name='Python')
    cou1.save()
    cou2.save()
    t1 = Teacher(tname='张老师')
    t1.save()
    t2 = Teacher(tname='王老师')
    t2.save()
    t3 = Teacher(tname='李老师')
    t3.save()
    t1.course.add(cou1)
    t1.course.add(cou2)
    t2.course.add(cou1, cou2)
    

    查询

    Course.objects.first().teacher_set.all()
    Teacher.objects.first().course.all()
    

    封装函数插入数据

    def insertData(tname,*coursenames):
        cour_name=[]
        
        for c in coursenames:
            try:
                cour = Course.objects.get(course_name=c)
            except Course.DoesNotExist:
                cour = Course.objects.create(course_name=c)
            cour_name.append(cour)
        t = Teacher(tname=tname)
        t.save()
        t.course.add(*cour_name)
    
    insertData('wanglaoshi','语文','数学')
    

    相关文章

      网友评论

          本文标题:Django-18-多对多

          本文链接:https://www.haomeiwen.com/subject/jritmhtx.html