[Answer]-Is there a way to simulate a foreach in Django using queries?

1👍

I ended up creating a list of the groups I was looking for and then querying all users that were in any of those groups. This should be pretty efficient as I’m only using one query.

statusGroups = []
    for group in status.groups.all():
        statusGroups.append(group)

    users = UserProfile.objects.filter(groupsIn__in=statusGroups)

0👍

As you haven’t posted your models, its a bit difficult to give you a django queryset answer, but you can solve your overlapping problem by adding your users to a set which doesn’t allow duplicates. For example:

from collections import defaultdict

users_by_status = defaultdict(set)

for i in Status.objects.all():
    for group in i.group_set.all():
        users_by_status[i].add(group.user.pk)

0👍

Based on your posted model code, the query for a given status is:

UserProfile.objects.filter(groupsIn__receivedStatuses=some_status).distinct()

I’m not 100% sure that the distinct() call is necessary, but I seem to recall that you’d risk duplicates if a given UserProfile were in multiple groups that share the same status. The main point is that filtering on many-to-many relationships works using the usual underscore notation, if you use the names as defined either by related_name or the default related name.

Leave a comment