neolaser
neolaser

Reputation: 6907

Django: ManyToMany filter matching to any item in a list

On a model blog I have a ManyToMany field called permissionGroups, which as the name suggests is a list of groups allowed to access something.

class blog(models.Model):    
    permissionGroups = models.ManyToManyField(groups, null=True, blank=True)
    ...

On another model groups I have a ManyToMany field called allowedUsers which again as the name suggests, is a list of users within that group.

class groups(models.Model):
    allowedUsers = models.ManyToManyField(User, null=True, blank=True)
    ...

So I want to be able to get all groups that the currentUser is in and match any one of those to any one of the permissionGroups of a specific blog.

I hope all that was clear,

Thanks in advance

Upvotes: 1

Views: 1737

Answers (1)

What's the final data you are looking for? A list of groups? A boolean "Can edit / can not edit"?

To check if a user belongs to a group that belongs to a blog, you can do this: user.groups_set.filter(blog=blog) This is the equivalent of checking if a user can edit said blog.

If you want a list of blogs that a user can edit, you can do this: blog.objects.filter(permissiongroups__in=user.groups_set.all())

Somehow thinking of your models was a mind bender.

Upvotes: 1

Related Questions