Search code examples
pythondjangodjango-ormgeneric-relationship

Django generic relations practice


i'm developing a authentication backend with object-based permissions for my django-app.I use generic relations between an object and a permission:

class GroupPermission(models.Model):
    content_t= models.ForeignKey(ContentType,related_name='g_content_t')
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_t', 'object_id')
    permission=models.ForeignKey(Permission)
    group = models.ForeignKey(Group)

And now i want to get all objects of a specified content type for which a сertain group or user has a сertain permission. What's the best way to do that? Shall i define the second end of the relation in the app's models? or better write custom sql? I'm trying to build a generic backend so i don't want it to depend on the app that is using it. Thanks!


Solution

  • I'm guessing you're looking for something like:

    perm = Permission.objects.get(pk=1) # pk #1 for brevity.
    group = Group.objects.get(pk=1)     # Again, for brevity.
    group_perms = GroupPermission.objects.filter(permission=perm, group=group)
    objects = [x.content_object for x in group_perms]
    

    This should get all of the objects which have the Permission of perm, and the Group of group into the variable objects.

    You could implement this into a Custom Manager class, as well:

    class GroupPermissionManager(models.Manager):
        def for(self, perm):
            group_perms = GroupPermission.objects.filter(permission=perm, group=self)
            objects = [x.content_object for x in group_perms]
    
    class Group(models.Model):
        name = models.CharField(max_length=30)
        permissions = GroupPermissionManager()
    

    Which would make your view code simpler:

    perm = Permission.objects.get(pk=1) # pk #1 for brevity.
    group = Group.objects.get(pk=1)     # Again, for brevity.
    objects = group.permissions.for(perm)