Home > other >  get all children of category id in a list drf
get all children of category id in a list drf

Time:11-07

I have a model like this

class Catgeory(models.Model):
      name = models.CharField()
      parent = models.ForeignKey('self', related_name='children')

Now I need to write a piece of code to return a list of all children ids for a specified category

for example, I have a category like that

General (id=1) --> Electronics (id=2) --> Mobile phones (id=3) --> Apple (id=4)

If I want to get children of Electronics it should return [3, 4] But I have been trying to find a solution for 3 hours, unfortunately, I could not solve it yet. I can get all parents by one child but cannot get children by a parent. If anybody has a solution or any idea, can you help? Any help would be appreciated! Thank you very much!

CodePudding user response:

you can try this

class Catgeory(models.Model):
    name = models.CharField()
    parent = models.ForeignKey('self', related_name='children')
    
    def get_all_child(self):
        children = []
        for u in self.children.all():
            children.append(u.get_all_child())
        return children

But you have to be sure that you do not have this (child==parent) because if you have this kind of case you will have an infinite loop.Be carefull.

CodePudding user response:

To get all child categories we can try bfs approach

models.py

class Catgeory(models.Model):
    name = models.CharField(max_length=60)
    parent = models.ForeignKey('self', related_name='children', on_delete=models.SET_NULL, null=True, blank=True)

views.py

from django.http.response import HttpResponse
from .models import Catgeory

# Create your views here.
def index(request):
    category        = Catgeory.objects.get(id=1)
    child_category  = Catgeory.objects.filter(parent=category)
    queue = list(child_category)
    while(len(queue)):
        next_children = Catgeory.objects.filter(parent=queue[0])
        child_category = child_category.union(next_children)
        queue.pop(0)
        queue = queue   list(next_children)
    return HttpResponse(child_category)
  • Related