Reputation: 862
models
class Permission(models.Model):
name = models.CharField(max_length=250, unique=True)
class PermissionDetail():
perm = models.ForeignKey(
Permission, on_delete=models.CASCADE, related_name='perm_details')
group = models.ForeignKey(
'Group', blank=True, null=True, related_name='group_perms', on_delete=models.CASCADE)
class Group():
name = models.CharField(max_length=250)
users = models.ManyToManyField(User, blank=True, related_name='groups')
permissions = models.ManyToManyField(Permission, blank=True, related_name='permissions')
what I did:
user_groups = user.groups.all()
perm_details = []
for group in user_groups:
perm_details.append(group.group_perms.filter(perm=perm))
return perm_details
This returns the correct list of data but I want queryset instead of list.
How can I return the queryset instead of making list here ?
I tried like this but Is's not right.
PermissionDetail.objects.filter(perm=perm, groups__pk__in=user_groups)
Upvotes: 0
Views: 407
Reputation: 177
The list you made perm_details
contains the query that you appended; which means you could access anything inside the model Group
if you iterate over that list.
But you don't need to create a list, you could simply add the user to your filter
Upvotes: 0
Reputation: 32294
You should be able to do this in a single query
PermissionDetail.objects.filter(
perm=perm,
group__users=user
)
You may need to add .distinct()
if you get duplicate results
Upvotes: 1