我正在尝试显示按类别组织的项目列表,其相应类别名称以粗体显示在其正上方。例如:
类别1
类别2
但是,这是当前代码的作用:
类别1
类别2
涉及的两个模型类来自/models.py:
class Model(models.Model):
model_number = models.CharField('Model Number', max_length = 50)
manufacturer = models.ForeignKey('Manufacturer', on_delete = models.SET_NULL, null = True)
category = models.ForeignKey('Category', on_delete = models.SET_NULL, null = True)
description = models.TextField(max_length = 1000, help_text = "Enter brief description of product", null = True) #TextField for longer descriptions
def __str__(self):
return f'{self.model_number}..........{self.description}'
def get_absolute_url(self):
#Returns the url to access a particular location instance
return reverse('model-detail', args=[str(self.id)])
class Category(models.Model):
category = models.CharField('Equipment Type', max_length = 50,
help_text = "Enter general category of equipment")
class Meta:
verbose_name_plural = "categories" #default would have shown as "Categorys" on admin page
def __str__(self):
return self.category
/model_list.html
{% extends "base_generic.html" %}
{% block content %}
<div style="margin-left:20px; margin-top:20px">
<h1>Model list</h1>
</div>
{% if model_list %}
{% for category in model_list %}
<li><strong>{{ category.category }}</strong></li>
<ul>
{% for model in model_list %}
<li>
<a href="{{ model.get_absolute_url }}"> {{ model.model_number }}..........{{ model.description }} </a>
</li>
{% endfor %}
</ul>
{% endfor %}
{% else %}
<p>There is no equipment in the database</p>
{% endif %}
{% endblock %}
答案 0 :(得分:1)
对于ForeignKey
字段,您可以从另一个字段访问一个“ Model
”的属性:
{% for model in models %}
{{ model.category.category }}
{{ model.category.help_text }}
{% endfor %}
本质上-将您在manufacturer
中位于上方的category
和Model
的字段视为存储对象的字段-一旦获得该字段-您的变量就不会字符串或整数,但这是Category
模型的实例。然后,您可以开始选择该模型的属性,也就是说model.category
是Category
对象的实例。
从组织模型的方式来看,想要实现的目标似乎有些棘手。我可能建议您考虑将您所有模型的分类折叠到一系列对象中:
在views.py
中:
models = [ { 'category': 'categoryName', 'objects': [ SomeModelInstance1 , ... ] } ]
然后:
{% for model in models %}
model.category
{% for object in model.objects.all %}
{{ object.name }}
{% endfor %}
{% endfor %}
让我知道这是否为您指明了正确的方向...很高兴为您提供帮助。