Skip to content
Advertisement

Django: How to mangle through relations

I have an instance of ModelA and want to query all instances of ModelC which are related to ModelA through ModelB.

ModelA -> all ModelB instances with FK rel_a = ModelA -> rel_c.all()

class ModelA(models.Model):
    # fields
    pass

class ModelB(models.Model):
    rel_a = models.ForeignKey('ModelA', ...)
    rel_c = models.ManyToMany('ModelC')
    # more fields

class ModelC(models.Model):
    # fields
    pass

I know how I would do this in SQL but I really do not get how I should unmangle these relations

Advertisement

Answer

You can query with a .filter(…) expression [Django-doc]:

ModelC.objects.filter(modelb__rel_a=instance_of_modela)

You can, like @IainShelvington says, use .distinct() [Django-doc] to filter out duplicates:

ModelC.objects.filter(modelb__rel_a=instance_of_modela).distinct()

If you specified a related_query_name=… [Django-doc] or a related_name=… [Django-doc] in the ManyToManyField from ModelB to ModelC (so rel_c), then the name of modelb is replaced with that, so then it is:

ModelC.objects.filter(related_relc__rel_a=instance_of_modela).distinct()

with related_relc the related_query_name or related_name in the rel_c field.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement