Py学习  »  Django

Django 2不同模型字段项

tootall • 4 年前 • 523 次点击  

我试图获取模块字段中不同项的列表,然后显示与该字段关联的所有项。

例如,在学校管理系统中有一个学校模块和一个学生模型。每个学生都有一个与他们相关联的颜色作为“颜色”字段。我想创建一个页面,该页面列出学校中所有不同的颜色,然后在每个颜色下列出属于该颜色的学生列表。

我可以在视图中编写这个函数吗?

以下是目前为止我在VIEWS.py中看到的:

class SchoolColorDetailView(DetailView):
    model=models.School
    template_name='school_app/school_color_detail.html'

    def get_context_data(self,**kwargs):
        context = super().get_context_data(**kwargs)
        context['colors']=Student.objects.all().order_by('color').distinct('color')

这会给我一份所有颜色的清单(但不是按学校)。有没有办法只得到学校的颜色,然后所有学生与该颜色相关联?我必须为此创建字典吗?

任何帮助都将不胜感激。

谢谢!

更新:

模型如下:

class School(models.Model):
    name = models.CharField(max_length=256)
    principal = models.CharField(max_length=256)
    location = models.CharField(max_length=256)


    def __str__(self):
        return self.name

    def get_absolute_url(self):
    return reverse("school_app:school_detail",kwargs={'pk':self.pk})


class Student(models.Model):
    name = models.CharField(max_length=256)
    color = models.CharField(max_length=256)
    school = models.ForeignKey(School,related_name='students', on_delete="Protect")

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("school_app:student_detail",kwargs={'pk':self.pk})

第二次更新:

我正在尝试创建一个类似这样的模板(不确定最好的方法):

{% for color in colors %}
 <ul>
   <li>{{color}}
     {% for student in color %}
     <ul>
       <li>{{student}}</li>
     </ul>
     {% endfor %}
   </li>
 </ul>
{% endfor %}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38340
 
523 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Chris Curvey
Reply   •   1 楼
Chris Curvey    5 年前

变化

context['colors']=Student.objects.all(
       ).order_by('color').distinct('color')

context['colors']=self.student_set.all(
       ).order_by('color').distinct('color')