Django LEFT JOIN or INNER JOIN the same query set together multiple times

Viewed 23

It's been a minute since I've used SQL so I'm not 100% sure LEFT or INNER join is the correct term, as I googled this and in most cases, people just wanted to concatenate the results, which is not SQL JOIN's. I have 3 models. Dumbed down they are as follows:

class Stakeholders(models.Model):
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    email = models.EmailField(max_length=254)

class Policy(models.Model):
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=150)

class StakeholderPolicyResp(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    stakeholder = models.ForeignKey(Stakeholders, on_delete=models.CASCADE)
    policy = models.ForeignKey(Policy, on_delete=models.CASCADE)
    response = models.IntegerField(default=0)

I want to create a table that has a unique stakeholder with the response for up to 4 policies.

In simple example:

Stakeholder
-------------------
1    John   Doe    jd@email.com

Policy
-------------------
1    Policy 1
2    Policy 2
3    Policy 3

StakeholderPolicyResp
-------------------
UID1   1    1   0
UID2   1    2   4
UID3   1    3   3

What I want out is a table that can have varying amount of columns, but something like this:

MyTable
------------------
Stakeholder data - Policy x Resp - Policy y Resp - Policy z Resp
==================
John | Doe | 0 | 4 | 3

Here we have the stakeholder with the responses for policy 1, policy 2 and policy 3. From here I'm going the render the data and doing that is fairly easy. It need not be in qs format. A possible format might be using pandas data frame, but is there an easier django'y way of doing it?

0 Answers
Related