[Answer]-Django query using through model

1👍

You need to define symmetrical=False when creating the field. In Django 1.7 if you try your definition you will get an error similar to this:

CommandError: System check identified some issues:

ERRORS:
myapp.MyModel.a: (fields.E332) Many-to-many fields with intermediate tables must not be symmetrical. 

so change the field to

a = models.ManyToManyField('self', through = 'x', symmetrical = False)

Now it all depends on your x class. It have to define two foreignKey fields back to yourModel:

class x(models.Model):
    from_a = models.ForeignKey(myClass, related_name = 'from_a')
    to_a = models.ForeignKey(myClass, related_name = 'to_a')
    comment = models.CharField(max_length = 255)

Now you don’t filter from x but from the reversed relations created by the FK’s, i.e. something like this:

myClass.objects.filter(from_a__comment='something')

or from an instance perspective:

my_instance.a.filter(from_a__comments='something')

A great article about the topic can be found here: Self-referencing many-to-many through

👤Todor

Leave a comment