Django get all records of related models
django, django-models, django-queryset, python
Solution
Use the double-underscore syntax to query across relationships.
All activities for user:
Activity.objects.filter(list__topic__user=my_user)
All activities for user for a topic:
Activity.objects.filter(list__topic=my_topic)
(Note that currently a Topic is for a single user only. Not sure if that's what you mean: you describe a user selecting a topic, which couldn't happen here. Potentially the link from Topic to UserProfile should go the other way, or be a ManyToMany.)
Problem
I have 3 models for a to-do list app: ``` class Topic(models.model) user = models.ForeignKey(UserProfile) lists = models.ManyToManyField(List) class List(models.model) activities = models.ManyToManyField(Activity) class Activity(models.model) activity = models.CharField(max_length=250) ``` This makes sense when a user selects a Topic, then a List (sub-category), which shows all activities on that list. But how would I efficiently query things like - All activities of user X (regardless topic or list) - All activities of topic X for user X (regardless of lists) Would I need to use `select_related()` in the query and than loop trough the related objects, or is there a more efficient way without looping? (Or should I change my models?)