Issue
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!
Solution
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)
Answered By - Pulkit Kumar Agarwal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.