我有一個這樣的模型
class Catgeory(models.Model):
name = models.CharField()
parent = models.ForeignKey('self', related_name='children')
現在我需要撰寫一段代碼來回傳指定類別的所有子 ID 的串列
例如,我有一個這樣的類別
General (id=1) --> Electronics (id=2) --> Mobile phones (id=3) --> Apple (id=4)
如果我想要獲得Electronics 的children應該回傳 [3, 4] 但是我已經嘗試了 3 個小時的解決方案,不幸的是,我還沒有解決它。我可以通過一個孩子獲得所有父母,但不能通過父母獲得孩子。如果有人有解決方案或任何想法,你能幫忙嗎?任何幫助,將不勝感激!非常感謝!
uj5u.com熱心網友回復:
要獲得所有子類別,我們可以嘗試 bfs 方法
模型.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)
視圖.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)
uj5u.com熱心網友回復:
你可以試試這個
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),因為如果你有這種情況,你將有一個無限回圈。小心。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/350415.html
標籤:Python 蟒蛇-3.x 姜戈 Django 休息框架
