About Creating Nested Categories Programmatically

You can create a category tree with django-treebeard programmatically as follows:

1
2
3
4
5
6
category_1 = Category.add_root(title="Python")
subcategory_1_1 = category_1.add_child(title="Django")
subcategory_1_2 = category_1.add_child(title="Flask")
category_2 = Category.add_root(title="JavaScript")
subcategory_2_1 = category_2.add_child(title="React")
subcategory_2_2 = category_2.add_child(title="Vue")

You can traverse your categories like this:

1
2
3
4
for category in Category.get_root_nodes():
    print(f"- {category.title}")
    for subcategory in category.get_children():
        print(f"  - {subcategory.title}")

Tips and Tricks Programming Development Django 3.2 Django 2.2 Django 1.11