Reputation: 5854
I have a Django model
class Category(models.Model):
parent = models.ForeignKey('Category', null=False, blank=False)
category_name = models.CharField(max_length=55,null=False, blank=False)
status = model.BooleanField(default=True)
I want to create recursive which return tree structure dict.
e.g
[
{
'category_name': 'vehical',
'id': 1,
'children' : [
{
'category_name': 'cars',
'id': 11,
'children': [
{
'category_name': 'sport cars',
'id': 20
}
]
}
]
}
]
>>> category = Category.objects.all()
>>> get_tree(category)
Upvotes: 2
Views: 1056
Reputation: 51978
I think you need to change your ForeignKey
relationship to self
, for referencing itself. Also, for simplicity of implementation, let us add related_name='children'
(doc) and make it nullable(null=True
) to denote it as a root node(s).
class Category(models.Model):
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
category_name = models.CharField(max_length=55,null=False, blank=False)
status = models.BooleanField(default=True)
Then we can do following implementation:
from django.forms.models import model_to_dict
def get_tree(category):
tree = model_to_dict(category, fields=['category_name', 'status', 'id'])
if category.children.all().exists():
children = list()
for child in category.children.all():
children.append(get_tree(child))
tree['children'] = children
return tree
final_tree = list()
for category in Category.objects.filter(parent__isnull=True):
final_tree.append(get_tree(category))
print(final_tree)
Upvotes: 4