[Fixed]-Django Combine Two Tables Through a Third

1👍

Use related_name on the ForeignKeys

from django.db import models


class ModelA(models.Model):
    name = models.CharField(max_length=50)


class ModelB(models.Model):
    property = models.CharField(max_length=50)


class ModelC(models.Model):
    a = models.ForeignKey(ModelA, related_name="theas")
    b = models.ForeignKey(ModelB, related_name="thebs")

To get all ModelB instances that relate to an instance of ModelA

a_inst = ModelA.objects.get(foo=bar)
ModelB.objects.filter(thebs__a=a_inst)

Leave a comment