How to get objects with a foreign key

I have a model category that has an FK link to itself. How can I send data to a template and make it look like

  • Category 1
    • List item
    • List item
  • Category 2
    • List item
    • List item
+4
source share
2 answers

It looks like you are trying to do recursion in templates. This may help: http://www.undefinedfire.com/lab/recursion-django-templates/

+2
source

Perhaps you are looking for something like this:

models.py

from django.db import models class Category(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey('self', blank=True, null=True, related_name='child') def __unicode__(self): return self.name class Meta: verbose_name_plural = 'categories' ordering = ['name'] 

views.py

 from myapp.models import Category # Change 'myapp' to your applications name. from django.shortcuts import render_to_response def category(request) cat_list = Category.objects.select_related().filter(parent=None) return render_to_response('template.html', { 'cat_list': cat_list }) 

template.html

 <ul> {% for cat in cat_list %} <li>{{ cat.name }}</li> <ul> {% for item in cat.child.all %} <li>{{ item.name }}</li> {% endfor %} </ul> {% endfor %} </ul> 
+3
source

All Articles