문제

IM 작업 카테고리 및 하위 범주 데이터 모드,이 부분에서는 모두 괜찮지 만 메뉴 NAV에서 내 카테고리와 하위 범주를 사용해야합니다. jQuery 메뉴 , 그리고 나는 내 메뉴를 하위 범주로 렌더링하지만, 하위 범주를 방해로 렌더링하면서 잃어 버렸습니다.

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

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

내 문제 : Datamodel에서 : '자기'를 사용하면 하위 범주를 만들기 위해이 경우에 얼마나 아픈지 알지 못합니다 (부모는 필드 자체) ..

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 the HTML for the top-level category
    for clc in tlc.child.all():
        #do the HTML for the children of clc

여러 레벨 카테고리가있는 경우 어딘가에 재귀적인 호출이 있어야하지만 기본 요점이 제공됩니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top