Joey
Joey

Reputation: 11

Join Many to Many tables in Django

I have three models, connected with many to many relationships

ModelA - M:N - Model B - M:N - Model C

They are defined as

ModelA
attA1
attA2

ModelB
attB1
att1s.ManyToManyField(ModelA)
att3s.ManyToManyField(ModelC)

ModelC
attC1
attC2

I want to store the data from these three on server start, without querying the database again - but I need all the data in each table.

The equivalent SQL for what I'm looking for is:

SELECT *
FROM ModelA, ModelB, ModelC
WHERE ModelA.pkA = ModelB.pkA AND ModelC.pkC=ModelB.pkC

Any help would be much appreciated!

Upvotes: 1

Views: 971

Answers (1)

Philip B.
Philip B.

Reputation: 637

Given:

class ModelA(models.Model):
    a = models.CharField(max_length=15)

class ModelC(models.Model):
    c = models.CharField(max_length=15)

class ModelB(models.Model):
    b = models.CharField(max_length=15)
    modela = models.ManyToManyField(ModelA)
    modelc = models.ManyToManyField(ModelC)

You can list out all the relationships by looping over ModelB and pulling in a and c like this:

ModelB.objects.values('modela__a', 'b', 'modelc__c')

Verified in Django shell

Upvotes: 4

Related Questions