获取列表 drf 中所有 children 个类别 ID

get all children of category id in a list drf

我有这样的模型

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

现在我需要写一段代码来return一个指定类别的所有children id的列表

例如,我有一个这样的类别

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

如果我想获得 children of Electronics 它应该 return [3, 4] 但是我已经尝试了3个小时的解决方案,不幸的是,我还没有解决。我可以通过一个 child 获得所有 parents 但不能通过 parent 获得 children。 如果有人有解决方案或任何想法,你能帮忙吗? 任何帮助,将不胜感激!非常感谢!

要获取所有子类别,我们可以尝试 bfs 方法

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)

你可以试试这个

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

但是你必须确定你没有这个(child==parent) 因为如果你有这种情况你将有一个无限的loop.Be carefull.