In Django, I have a Checkout model that is a ticket for someone checking equipment. I also have an OrganizationalUnit model, which includes the Checkout model (via ForeignKey), since the person at the checkout belongs to OrganizationalUnit on our campus.
OrganizationalUnit is related to itself, therefore several departments can be children of a certain department, and these children can have children, etc. Here are some simplified models.
class OrganizationalUnit(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey(
'self',
blank=True, null=True,
related_name='children',
)
class Checkout(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
department = models.ForeignKey(
OrganizationalUnit,
null=True,
blank=True,
related_name='checkouts',
)
I want to get a Checkouts account associated with a specific OrganizationalUnit and all its children. I know how to get an account of all OU related checks.
ou = OrganizationalUnit.objects.get(pk=1)
count = ou.checkouts.all().count()
, OU ? - ?
. , while, . , , 5 . ...
for kid in ou.children.all():
child_checkout_count += kid.checkouts.all().count()
for kid2 in kid.children.all():
child_checkout_count += kid2.checkouts.all().count()
for kid3 in kid2.children.all():
child_checkout_count += kid3.checkouts.all().count()
for kid4 in kid3.children.all():
child_checkout_count += kid4.checkouts.all().count()
for kid5 in kid4.children.all():
child_checkout_count += kid5.checkouts.all().count()
... . , . ! ( , , .)