【问题标题】:Django, category and subcategoriesDjango,类别和子类别
【发布时间】:2010-11-28 14:26:39
【问题描述】:

我使用DataModel 工作类别和子类别,这部分一切都很好,但我需要在我的菜单导航中使用我的类别和子类别,我尝试使用这个Jquery menu,并且我渲染我的菜单子类别,但我在渲染子类别时迷失了方向:

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

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

我的问题:在数据模型中:使用“自我”,我不知道在这种情况下为子类别做一个 for (父级是字段本身)有多糟糕。..

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")

谢谢

【问题讨论】:

    标签: jquery css django django-models django-templates


    【解决方案1】:

    使用类似的东西获取所有顶级类别

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

    然后:

    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
    

    如果您有多个级别的类别,则需要在某处进行递归调用,但这给出了基本要点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-28
      • 2011-01-04
      • 1970-01-01
      • 2015-04-05
      • 2017-06-17
      • 2012-10-14
      相关资源
      最近更新 更多