Reputation: 1418
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
?
(Suggestions for better question title are welcome)
Upvotes: 0
Views: 31
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)
Upvotes: 1
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