从django的三个模型中获取特定数据

时间:2015-06-28 13:15:04

标签: python django django-templates django-views

我开始使用django,我想从三个相关模型中获取特定数据。 我的模特是

class Institution(models.Model):
    name = models.CharField(max_length=100, unique=True)
    ...

class Certification(models.Model):
    name = models.CharField(max_length=100)
    ...

class Course(models.Model):
    name = models.CharField(max_length=100)
    institution = models.ForeignKey(Institution)
    certification = models.ForeignKey(Certification)

在我的html页面中,我希望显示由认证订购的特定机构提供的课程。像这样

name of a particular institution I 
    certification 1
         list courses that offer certification 1
    certification 2
         list courses that offer certification 2
    ...

我当前的模板是

{{institution.name}}
{% for certification in preselected_certifications %}
    <h1> {{ certification.name }} </h1>
    <ul>
          {% for course in courses %}
            <li>{{ course.name }}</li>
          {% endfor %}
    </ul>
{% endfor %}

我的观点

def detail(request, slug):
    context = RequestContext(request)
    context_dict = {'slug_requested': slug}
    try:
      institution = Institution.objects.get(slug=slug)
      courses = Course.objects.filter(etablissement=etablissement)

      context_dict['courses'] = courses
      context_dict['institution'] = institution

    except Institution.DoesNotExist:
      pass

    return render_to_response('institutition/details.html', context_dict, context)

我的问题是如何定义&#34; preselected_certifications&#34;所以它只包含所选机构所有课程提供的证书,但不重复任何认证

2 个答案:

答案 0 :(得分:0)

问题:

  

如何定义&#34; preselected_certifications&#34;所以它只包含所选机构所有课程提供的证书,但不重复任何认证

我不确切地知道您希望如何表示这些信息(意思是,您想要哪些属性),但您认为您需要以下内容:

def detail(request, slug):
   ...
   institution = Institution.objects.get(slug=slug)

   # `select_related` not strictly necessary
   courses = institution.course_set.all().select_related('certification')

   context_dict['courses'] = courses
   context_dict['institution'] = institution

现在,每个course对象都可以访问其certification关系,而可以遍历它们以显示唯一的关系。

但是,如果您想从一开始就确保这些certification是唯一的,那么另一种方法是使用另一个查询:

   institution = Institution.objects.get(slug=slug)
   courses = institution.course_set.select_related('certification')
   certification_ids = courses.values_list('certification_id', flat=True).distinct()
   preselect_certifications = Certification.objects.filter(id__in=certification_ids)

最后一个查询将为您提供特定机构的独特认证。

似乎Certification可能与Institution有关系,但不是吗?

答案 1 :(得分:0)

非常感谢,现在我在我的模板中使用以下代码

{% for certification in preselect_certifications %}
   {{certification.name}} 
   {% for course in courses %}
      <ul>
      {% if certification = course.certification %}
         <li>{{ course.name }}</li>
      {% endif %}
      </ul>
   {% endfor %}
{% endfor %}

它完美无缺,但有另一种方法可以避免使用

{% if certification = course.certification %}

再次感谢