0

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)
D_P
  • 802
  • 10
  • 32
  • You can directly returns user_groups but what the perm here ? group.group_perms.filter(perm=perm) – Mythily Devaraj May 12 '21 at 07:15
  • if you have two different models, you can use `itertools.chain` [issue 431628](https://stackoverflow.com/questions/431628/how-can-i-combine-two-or-more-querysets-in-a-django-view). If queryset uses the same model, it may be possible with the `|`-operator [article](https://simpleisbetterthancomplex.com/tips/2016/06/20/django-tip-5-how-to-merge-querysets.html) – Klim Bim May 12 '21 at 07:17

2 Answers2

1

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

Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Astros
  • 179
  • 1
  • 10