对于以下的模型:html
from django.db import models # Create your models here. class Student(models.Model): name = models.CharField(max_length=128) class Course(models.Model): name = models.CharField(max_length=128) students = models.ManyToManyField('Student')
模型Course有一个多对多字段指向Student模型。django
假设编写了一个以下的视图:spa
def test(request): course = models.Course.objects.get(pk=1) return render(request, 'course.html', locals())
获取了id为1的course对象,并将它传递给course.html模版,模版代码以下:code
{% for student in course.students.all %}
<p>{{ student.name }}</p> {% endfor %}
首先经过course.students.all
,查寻到course对象关联的students对象集,而后用for标签循环它,获取每一个student对象,再用student模型的定义,访问其各个字段的属性。htm
对于反向查询,从student往course查,假设有以下的视图:对象
def test2(request): student = models.Student.objects.get(pk=1) return render(request, 'student.html', locals())
获取了id为1的student对象,并将它传递给student.html模版,模版代码以下:get
{% for course in student.course_set.all %} {{ course.name }} {% endfor %}
经过student.course_set.all
,反向获取到student实例对应的全部course对象,而后再for标签循环每一个course,调用course的各类字段属性。it
对于外键ForeignKey,其用法基本相似。只不过正向是obj.fk
,且只有1个对像,不是集合。反向则是obj.fk_set
,相似多对多。class