繁体   English   中英

Django - 循环遍历模板中的唯一模型字段

[英]Django - Looping over unique model field in template

我有一个模型,其中有一个选择字段category ,用户在提交条目时必须输入该字段。 我想创建一个视图,其中每个类别都有自己的标题(只有一次),因此每个唯一的类别都有自己的标题,然后显示与每个类别关联的title

模型.py

class Position(models.Model):
    club_functions = Choices('Corporate Relations', 'Events & Conference', 'Marketing & Operations', 'Software Development', 'Product')
    title = models.CharField(max_length=50)
    category = models.CharField(choices=club_functions, max_length=30, blank=False)
    description = models.TextField(blank=True)
    spec_q1 = models.CharField(max_length=500)
    spec_q2 = models.CharField(max_length=500)

视图.py

def position_list_view(request):
    all_objects = Position.objects.all()
    context = {
        'object_list' : all_objects
    }
    return render(request, "exec_list.html", context)

exec_list.html

{% for object.category in object_list %}

    <h3>{{ object.category }}</h3>
    <p>{{ object.title }}</p>


{% endfor %}

关于如何做到这一点的任何想法?

你可以使用重组

{% regroup object_list by category as category_list %}

<ul>
    {% for category in category_list %}
        <li>{{ category.grouper }}
            <ul>
            {% for position in category.list %}
                <li>{{ position.title }}</li>
            {% endfor %}
            </ul>
        </li>
    {% endfor %}
</ul>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM