[Fixed]-Optimizing Django Many-To-Many Query with custom through table

1👍

I don’t see anything inefficient about that query, you’ll have to debug your problem more precisely.

That said, you can achieve the same thing more simply (and equally efficiently) by just using a related name on the through table.

class ModelA(models.Model):
    fieldA = models.ManyToManyField(ModelB, through="CustomThroughTable")

class ModelB(models.Model):
    whatever = models.CharField()

class CustomThroughTable(models.Model):
    modela = models.ForeignKey(ModelA, related_name="foobar")
    modelb = models.ForeignKey(ModelB)

Leave a comment