Django,类别和子类别 [英] Django, category and subcategories

查看:156
本文介绍了Django,类别和子类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 DataModel 来处理工作类别和子类别,在这一部分都可以,但是我需要在我的菜单导航中使用我的类别和子类别,尝试使用此 Jquery菜单,并且使用子类别来呈现我的菜单,但是丢失以如下方式呈现子类别:

 < ul> 
< li>
< a href =#>类别< / a>

<! - subcategories - >
< span>子类别1< / span>
< span>子类别2< / span>
...
< / li>
....
....
< / ul>

我的问题:在数据模型中:使用'self',我不知道如何做。

  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)

感谢

解决方案

使用类似

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

然后:

  for tlc in top_level_cats:
#do顶级类别的HTML
在tlc.child.all()中的clc:
#do clc的子项的HTML

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


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

解决方案

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.

这篇关于Django,类别和子类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆