Crossfire
Crossfire

Reputation: 1861

Check if many to many child objects share a parent in Django

I have these simple models in Django. Given two accounts acc1 and acc2, what is the best way to figure out if they are both participating in the same team? I'm trying to keep this as concise as possible (because this was to be a lambda, no named variables).

class Team(models.Model):
    members = models.ManyToManyField(Account, through='Participation')

class Participation(models.Model):
    team = models.ForeignKey(Team, on_delete=models.CASCADE)
    account = models.ForeignKey(Account, on_delete=models.CASCADE)

So far what I've got:

def are_in_same_team(acc_pk1, acc_pk2):
    teams = Team.objects.filter(participation__account__id__in=[acc_pk1, acc_pk2])
    return (acc_pk1 == acc_pk2 and len(teams) == 1) or (len(teams) == 2 and teams[0] == teams[1])

Upvotes: 2

Views: 655

Answers (1)

AKS
AKS

Reputation: 19841

You could check if there exists a team which have both the members:

def are_in_same_team(acc_pk1, acc_pk2):
    return Team.objects.filter(members__id=acc_pk1).filter(members__id=acc_pk2).exists()

Upvotes: 3

Related Questions