This logic is hard to follow. How about building up a list of possible groups (in order that they should be tried), and then checking them in a loop. And, while you're at it, can you change the query to `Group.objects.filter(name=groupname).exists()`?