[Answered ]-How Do I Select all Objects via a Relationship Model

2πŸ‘

βœ…

Do you definitely need it to be a queryset? If you only need it to be an iterable, a simple expression for your purposes is:

profiles = [r.profile for r in thingie.relation_set.all()]

I’m not sure if a list comprehension counts as irritating iterating, but to me this is a perfectly intuitive, pythonic approach. Of course if you need it to be a queryset, you’re going to do something messier with two queries, eg:

relation_values = thingie.relation_set.all().values_list('pk', flat=True)
profiles = Profile.objects.filter(relation__in=relation_values)

See the β€œin” documentation for more. I prefer the first approach, if you don’t need a queryset. Oh and if you only want distinct profiles you can just take set(profiles) in the first approach or use the distinct() queryset method in the second approach.

πŸ‘€ozan

0πŸ‘

Did you read the Django doc on Making queries? It has a simple example of achieving what you want, more specifically Lookups that span relationships. Make sure you refer the code snippets in the latter link to the model code at the beginning of the page.

πŸ‘€Thierry Lam

0πŸ‘

Without defining a direct relationship between Profile and Thingie, you can’t.

The best way would be to add a ManyToMany to Thingie that points to Profile and use the through argument (django docs) on the ManyToMany to specify your Relation model/table.

That way you can do a direct filter operation on Thingie to get your profiles and still store your intermediate Relation data.

Leave a comment