# How to output a queryset from inter-related tables/models

**URL:** <https://forum.djangoproject.com/t/how-to-output-a-queryset-from-inter-related-tables-models/17866>\
**Category:** Using the ORM\
**Created:** [December 27, 2022, 3:41pm UTC](https://forum.djangoproject.com/t/how-to-output-a-queryset-from-inter-related-tables-models/17866 "2022-12-27T15:41:55Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![onyeibo](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/onyeibo/32/11494_2.png) [@onyeibo](https://forum.djangoproject.com/u/onyeibo)\
**Post date:** [December 27, 2022, 3:41pm UTC](https://forum.djangoproject.com/t/how-to-output-a-queryset-from-inter-related-tables-models/17866/1 "2022-12-27T15:41:55Z")

</div>

![output](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/2X/c/c40492579f9c13d521c07d553341888bb4f85b0f.jpeg)

I like to illustrate my challenges. Hopefully it helps. I have the following models/tables:

1. Firm
2. Worker
3. Project
4. Manager
5. Task

A worker can be in one ore more firms and render service via one or more managers. Managers run projects and assign tasks to the workers while taking note of the firm that those workers represent.

In Django, I defined the relationship as follows:

```auto
from django.db import models
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator
 
# Create your models here.
 
 
class Firm(models.Model):
    """A company"""
 
    name = models.CharField(max_length=200)
    vision = models.TextField()
 
    def __str__ (self):
        """About company"""
 
        return self.name
 
 
class Worker(models.Model):
    """A worker in a company"""
 
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    firm = models.ForeignKey(
        Firm,
        on_delete=models.CASCADE,
        related_name="workers",
    )
    on_duty = models.BooleanField(default=True)
 
    def __str__ (self):
        """About worker"""
 
        return "{0}, {1}".format(self.last_name, self.first_name)
 
 
class Project(models.Model):
    """A Project in a firm"""
 
    name = models.CharField(max_length=200)
    deadline = models.DateTimeField(default=timezone.now)
 
    def __str__ (self):
         """About Project"""
 
         return self.name
 
 
class Manager(models.Model):
    "A consultant managing the project"
 
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    designation = models.CharField(max_length=200)
    project = models.ForeignKey(
        Project,
        on_delete=models.CASCADE,
        related_name="projmgrs",
    )
    firm = models.ForeignKey(
        Firm,
        on_delete=models.CASCADE,
        related_name="firmgrs",
    )
 
    def __str__ (self):
         """About Manager"""
 
         return self.designation
 
 
class Task(models.Model):
    """A Specific Task with paying points"""
 
    title = models.CharField(max_length=200)
    point = models.IntegerField()
    worker = models.ForeignKey(
        Worker,
        on_delete=models.CASCADE,
        related_name="worktasks",
    )
    manager = models.ForeignKey(
        Manager,
        on_delete=models.CASCADE,
        related_name="mgrtasks",
    )
    state = models.IntegerField(
        default=0,
        validators=[
            MaxValueValidator(100),
            MinValueValidator(0),
        ]
    )
    date = models.DateTimeField(default=timezone.now)
 
    def __str__ (self):
        """About Task"""
 
        return "{}%".format(self.state)

```

I want to be able to generate a table listing each worker, points accrued per task and the totals as illustrated in the diagram. I could iterate the worker and run a query per worker … but I suspect there is a way to pull all that data with one query.

Here is what I could come up with:

`Manager.objects.get(pk=1).firm.workers.filter(on_duty__exact=True).prefetch_related("worktasks").annotate(points=Sum("worktasks__point")).values()`

I see the points are there in the annotation but there is a problem with the above query. It pulls points for all works done by each worker (that’s every project). How do I filter that down to specific projects?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 27, 2022, 4:13pm UTC](https://forum.djangoproject.com/t/how-to-output-a-queryset-from-inter-related-tables-models/17866/2 "2022-12-27T16:13:33Z")

</div>

See the use of the [`filter`](https://docs.djangoproject.com/en/4.1/topics/db/aggregation/#filtering-on-annotations) parameter within the `annotate` function. Also see the examples in the [Cheat sheet](https://docs.djangoproject.com/en/4.1/topics/db/aggregation/#cheat-sheet).

---

<div class="post-metadata">

**Author:** ![onyeibo](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/onyeibo/32/11494_2.png) [@onyeibo](https://forum.djangoproject.com/u/onyeibo)\
**Post date:** [December 27, 2022, 6:53pm UTC](https://forum.djangoproject.com/t/how-to-output-a-queryset-from-inter-related-tables-models/17866/3 "2022-12-27T18:53:30Z")

</div>

> [@KenWhitesell](#):
>
> See the use of the [`filter`](https://docs.djangoproject.com/en/4.1/topics/db/aggregation/#filtering-on-annotations) parameter within the `annotate` function.

I tried this earlier, I think I was doing it wrong. Now that you referred to it again … I gave it more time and attention. It worked!

**Here is the final query:**

`Manager.objects.get(pk=1).firm.workers.filter(on_duty__exact=True).prefetch_related("worktasks").annotate(points=Sum("worktasks__point", filter=Q(worktasks __manager__ id__exact=1))).values()`

Thank you!

In the above example, I get sum of points for tasks executed under a specific manager

---

<div class="post-metadata">

**Author:** ![onyeibo](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/onyeibo/32/11494_2.png) [@onyeibo](https://forum.djangoproject.com/u/onyeibo)\
**Post date:** [February 19, 2025, 9:25am UTC](https://forum.djangoproject.com/t/how-to-output-a-queryset-from-inter-related-tables-models/17866/4 "2025-02-19T09:25:22Z")

</div>

Two years later, this answer still saves me. Thanks @KenWhitesell
