首页 > 其他 > 详细

DjangoORM一对多&多对多操作

时间:2016-04-23 10:17:51      阅读:218      评论:0      收藏:0      [点我收藏+]

简要说明

通过操作对象的方式操作数据库

详细步骤

models.py的结构是:

技术分享

如果models.py中外键定义没有写 related_name=’student_teacher’, 可以直接用

studentList = teacher.student_teacher.all() 可以改写成:

teacher = Teacher.objects.get(id = 1)

studentList = teacher.student_set.all()

============================================================================================

from myblog.models import Student,Teacher

def student_list(request):

t = loader.get_template("student_list.html")

#studentList = Student.objects.all()

teacher = Teacher.objects.get(id = 1)

studentList = teacher.student_teacher.all()

c = Context({"studentList":studentList})

return HttpResponse(t.render(c))

数据库一对多的操作:

查找:

方法一:

通过Student表来查:

查找Student表中,teacher_id为1的老师名称

studentList = Student.objects.all()

模板中使用:

student.teacher.name来获取外键的name属性值

方法二:

通过Teacher表来查:

teacher = Teacher.objects.get(id = 1) #先查到id 为1 的teacher
studentList = teacher.student_teacher.all() #通过外键查到studentlist

新增

方法一:

通过teacher得到student_set来创建
teacher.student_set.create(name = "tom",...)

方法二:

创造一个student对象,添加到teacher的student_set属性中
student = Student(name = "tom",....)
teacher.student_set.add(student)

修改

只删除student

  1. teacher = Teacher.objects.get(id = 1)
  2. student = teacher.student_set.get(id = 1)
  3. student.delete()

删除和该teacher相关的所有student

  1. teacher = Teacher.objects.get(id = 1)
  2. student = teacher.student_set.get(id = 1)
  3. student.teacher.delete()

数据库多对多操作:

  1. group = Group.objects.get(id = 1)
  2. studentList = group.members.all()
  3. groupList = student.group_set.all()
  4. MemberShip(group = newGroup, student=newStudent).save()




DjangoORM一对多&多对多操作

原文:http://www.cnblogs.com/echorep/p/5423873.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!