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()

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]:

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

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:

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