Django, category and subcategories

女生的网名这么多〃 提交于 2019-12-05 07:20:45

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/1429410/django-category-and-subcategories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!