I'm a django n00b and am lost on how to do this.
sample models:
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)
And some data:
v = Food_Type(name='Veggie')
f = Food_Type(name='Fruit')
c = Food(food_type=v, name='carrot')
a = Food(food_type=f, name=开发者_StackOverflow'apple')
The HTML output should look something like this:
Veggie
carrotFruit
appleI'm uncertain of the right way to do the grouping, I assume the view and not the template.
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} )
based on my view, I'm uncertain how to display
Does not work and there has got to be a better way
{% for type in food_type %}
{{ type }}
{% for food in foods %}
{% if food.food_type == type %}
{{ food.name }}
{% endif %}
{% endfor %}
{% endfor %}
I think you are looking for 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>
Simple:
Food.objects.order_by('food_type__name')
精彩评论