我是django n00b,我对如何做到这一点感到迷茫。
样本模型:
class Food_Type(models.Model):
name = models.CharField(max_length=200)
class Food(models.Model):
name = models.CharField(max_length=200)
food_type = models.ForeignKey(Food_Type)
还有一些数据:
v = Food_Type(name='Veggie')
f = Food_Type(name='Fruit')
c = Food(food_type=v, name='carrot')
a = Food(food_type=f, name='apple')
HTML输出应如下所示:
素食
胡萝卜
水果
苹果
我不确定进行分组的正确方法,我假设视图而不是模板。
food_type_list = Food_Type.objects.all().order_by('name')
food_list = []
for ft in food_type_list:
food_list.append(Food.objects.filter(fruit_type__exact=device_type.id)
render_to_response(some_template,
{'food_type': food_type_list, 'foods': food_list}
)
根据我的观点,我不确定如何显示
不起作用,必须有更好的方法
{% for type in food_type %}
{{ type }}
{% for food in foods %}
{% if food.food_type == type %}
{{ food.name }}
{% endif %}
{% endfor %}
{% endfor %}
答案 0 :(得分:2)
我认为您正在寻找regroup
food = Food.objects.all()
{% regroup food by food_type as food_list %}
<ul>
{% for food_type in food_list %}
<li>{{ food_type.grouper }}
<ul>
{% for item in food_type.list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
答案 1 :(得分:0)
简单:
Food.objects.order_by('food_type__name')