Question

im working category and subcategories with the DataModel, all is fine in this part, but i need to use my category and subcategories in my Menu Nav, im try to use this Jquery menu , and im rendering my menu with subcategories, but im lost with rendering the subcategories in the way:

<ul>
  <li>
    <a href="#">Category</a>

    <!--subcategories-->
   <span>Subcategory 1 </span>
   <span>Subcategory 2 </span>
   ...
  </li>
  ....
  ....
 </ul>

My problem: in the datamodel: with the 'self', i dont know how ill do a for in this case for make the subcategories (parent is the field himself)..

class Category(models.Model):
 name = models.CharField(core=True, maxlength=200)
 slug = models.SlugField(prepopulate_from=('name',))
 parent = models.ForeignKey('self', blank=True, null=True, related_name='child')
 description = models.TextField(blank=True,help_text="Optional")

Thanks

Was it helpful?

Solution

Get all top-level categories using something like

top_level_cats = Category.objects.filter(parent__isnull=True)

Then:

for tlc in top_level_cats:
    #do the HTML for the top-level category
    for clc in tlc.child.all():
        #do the HTML for the children of clc

If you have multiple level categories, there'll need to be a recursive call in there somewhere, but this gives the basic gist.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top