from django.db import models class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name
from myapp.models import Category # Get all categories categories = Category.objects.all() # Get a specific category category = Category.objects.get(id=1) # Get categories with a specific name categories = Category.objects.filter(name__contains='electronics')
from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.nameThis code creates a Category model with a hierarchical structure using the django-mptt library. The parent field is a TreeForeignKey that references itself, indicating it is a hierarchical category. The MPTTMeta class configures the order of insertion by name. The __str__ method returns the category name. Package library: django-mptt