Åsmund
Åsmund

Reputation: 1418

Querying ManyToMany relationships

I have a bunch of stations that belong in groups. Each station can be in multiple groups. This is the model (simplified):

class Station(models.Model):
    name = models.CharField(max_length=4, blank=False, primary_key=True)

    def __str__(self):
        return "Station " + self.name



class StationGroup(models.Model):
    name = models.CharField(max_length=100, blank=False, primary_key=True)
    stations = models.ManyToManyField(Station)

    def __str__(self):
        return "Station group " + self.name

How can I get a list/queryset containing

  1. stations that are not in any group
  2. stations that are in N groups
  3. the intersection, union and difference of N stationGroups

?

(Suggestions for better question title are welcome)

Upvotes: 0

Views: 31

Answers (2)

Sam Bobel
Sam Bobel

Reputation: 1824

To add to Daniel's answer, to get objects that are in ANY of a list of groups, you do

Station.objects.filter(stationgroup=g1).filter(stationgroup=g2).filter(stationgroup=g3)

Docs Here

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599490

Not in any group:

Station.objects.filter(stationgroup=None)

in N groups:

Station.objects.annotate(group_count=Count('stationgroup')).filter(group_count=N)

intersection/difference - there aren't any built-in ways of doing this. One possibility is to simply query the groups, convert them to sets and do the comparisons in Python. Or, you could write custom query expressions to do what you want.

Upvotes: 2

Related Questions