Home > Software engineering >  Python, Django: Query on combined models?
Python, Django: Query on combined models?

Time:12-10

inside my app I have multiple models, like:

models.py:

class Company(models.Model):
    name = models.CharField(max_length=100)


class Coworker(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    company = models.ForeignKey(Company, null=False, blank=False, on_delete=models.CASCADE)

As you can see, a Company can contain one, multiple or no Coworker! Is it possible to query Company but also receive the data from connected Coworker? For example something like this:

id    |    Company    |    Coworker
1     |    Company_A  |    Coworker_A
2     |    Company_B  |    
3     |    Company_C  |    Coworker_B
4     |    Company_C  |    Coworker_C
5     |    Company_C  |    Coworker_D
6     |    Company_D  |    Coworker_E
7     |    Company_D  |    Coworker_F
8     |    Company_E  |    
9     |    Company_F  |    Coworker_G
10    |    Company_F  |    Coworker_H
...

My problem is, that I can't query on the Coworker, because I don't want to miss those Companies that have no related data!

Thanks for your help and have a great day!

CodePudding user response:

Quite simply, query by company and prefetch results for workers :

Company.objects.prefetch_related("coworker_set").all()

What this will do is give you a list of companies containing their list of workers in the attribute coworker_set. It will also populate those attributes in a single query (that's the whole point of prefetch_related).

More specifically, here is how you could use such a query :

for company in Company.objects.prefetch_related("coworker_set").all():
    print(company.name)
    for coworker in company.coworker_set.all():
        print(coworker.first_name)
        print(coworker.last_name)

This guarantees that you will iterate through all companies as well as through all coworkers, and you will only iterate through each one once (indeed, if you queried by coworkers you would see some companies multiple times and others none at all).

  • Related