【问题标题】:How can i list Parent categories only with django-mptt?如何仅使用 django-mptt 列出父类别?
【发布时间】:2020-12-06 14:27:56
【问题描述】:

我只想在一个页面中列出父类别,而在另一个页面中列出其他子类别。

models.py

class Category(MPTTModel):
    name=models.CharField(max_length=50)
    slug=models.SlugField(max_length=50, unique=True, help_text='Uniue Value product page url, created from name.')
    is_active=models.BooleanField(default=True)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)
    parent=TreeForeignKey('self',on_delete=models.CASCADE,null=True,blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by=['name']

views.py

def index(request):
    listing=Category.objects.all()

    context={
        'listing':listing
    }
    return render(request,'catalog/index.html',context)

【问题讨论】:

  • “有孩子”中的父母,还是“没有父母”中的父母(所以 root 元素)?

标签: python python-3.x django django-models django-views


【解决方案1】:
def index(request):
    parents = Category.objects.filter(parent=None)

    context={
        'parents': parents,
    }
    return render(request,'catalog/index.html',context)

子类别使用:

    Category.objects.exclude(parent=None)

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    相关资源
    最近更新 更多