简体   繁体   中英

How can i list Parent categories only with django-mptt?

I want to list only the parent Categories in one page and the other sub-categories in another page.

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)
def index(request):
    parents = Category.objects.filter(parent=None)

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

sub-categories use:

    Category.objects.exclude(parent=None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM