Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 592241
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T15:43:10+00:00 2026-05-13T15:43:10+00:00

In Django, I’ve got a Checkout model, which is a ticket for somebody checking

  • 0

In Django, I’ve got a Checkout model, which is a ticket for somebody checking out equipment. I’ve also got an OrganizationalUnit model that the Checkout model relates to (via ForeignKey), as the person on the checkout belongs to an OrganizationalUnit on our campus.

The OrganizationalUnit has a self relation, so several OUs can be the children of a certain OU, and those children can have children, and so on. Here are the models, somewhat simplified.

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 count of the Checkouts that are related to a certain OrganizationalUnit and all of its children. I know how to get the count of all the checkouts that are related to an OU.

ou = OrganizationalUnit.objects.get(pk=1)
count = ou.checkouts.all().count()

But how do I make that count reflect the checkouts of this OU’s children and their children? Do I use some sort of iterative loop?


EDIT: I guess I still can’t quite wrap my head around the while command to do this. The organizational units can go as deep as the user wants to nest them, but right now the most it goes in the DB is 5 deep. I’ve written this…

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()

…which is total crap. And it takes a while to run because it pretty much traverses a major chunk of the database. Help! (I can’t seem to think very well today.)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T15:43:10+00:00Added an answer on May 13, 2026 at 3:43 pm

    I think the most efficient way of calculating this is at write time. You should modify OrganizationalUnit like this:

    class OrganizationalUnit(models.Model):
        name = models.CharField(max_length=100)
        parent = models.ForeignKey(
            'self',
            blank=True, null=True,
            related_name='children',
        )
        checkout_number = models.IntegerField(default=0)
    

    create the functions that will update the OrganizationalUnit and its parents at write time:

    def pre_save_checkout(sender, instance, **kwargs):
        if isinstance(instance,Checkout) and instance.id and instance.department:
             substract_checkout(instance.department)
    
    def post_save_checkout(sender, instance, **kwargs):
        if isinstance(instance,Checkout) and instance.department:
             add_checkout(instance.department)
    
    def  substract_checkout(organizational_unit):
        organizational_unit.checkout_number-=1
        organizational_unit.save()
        if organizational_unit.parent:
            substract_checkout(organizational_unit.parent)
    
    def  add_checkout(organizational_unit):
        organizational_unit.checkout_number+=1
        organizational_unit.save()
        if organizational_unit.parent:
            add_checkout(organizational_unit.parent)
    

    now all you need is connect those functions to the pre_save, post_save and pre_delete signals:

    from django.db.models.signals import post_save, pre_save, pre_delete
    
    pre_save.connect(pre_save_checkout, Checkout)
    pre_delete.connect(pre_save_checkout, Checkout)
    post_save.connect(post_save_checkout, Checkout)
    

    That should do it…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 290k
  • Answers 290k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer From the jQuery UI docs, it's based on your computer's… May 13, 2026 at 5:51 pm
  • Editorial Team
    Editorial Team added an answer Absolutely - create an appropriate ClassLoader instance, e.g. using URLClassLoader.… May 13, 2026 at 5:51 pm
  • Editorial Team
    Editorial Team added an answer You should have a look at setting DisplayAlerts=false Application.DisplayAlerts Property… May 13, 2026 at 5:51 pm

Related Questions

In Django, I've got loggers all over the place, currently with hard-coded names. For
In Django, I know using filter with multiple arguments gets translated into SQL AND
In Django, I have two models: class Product(models.Model): name = models.CharField(max_length = 50) categories
In Django (1.0.2), I have 2 models: Lesson and StatLesson. class Lesson(models.Model): contents =
In Django, I have images stored in site_media like this : /site_media/somepath/image.jpg The urls.py

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.