Wednesday, September 21, 2016

Basic GenericForeignKey Question

Hey all,

I'm just getting started with GenericForeignKeys and I've run into a small point of confusion. I'm implementing a very general permission system as follows:

class Permission(models.Model):
   
"""
    This stores permissions for a single object.
    """

   
#These 3 fields are used to implement a generic foreign key
    content_type
= models.ForeignKey(ContentType)
    object_id
= models.PositiveIntegerField()
    model
= GenericForeignKey()

    user
= models.ForeignKey(User)

   
#Permissions
    read
= models.BooleanField(default=False)
    write
= models.BooleanField(default=False)
   
delete = models.BooleanField(default=False)



I also have a check permission function as follows:
    def checkPermission(self, obj, user, action):
       
try:
            p
= Permission.objects.get(model=obj, user=user)
           
return getattr(p, action)
       
except ObjectPermission.DoesNotExist:
           
return False

Currently this fails because I'm trying to access the GenericForeignKey directly, and I get this error:
django.core.exceptions.FieldError: Field 'model' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation.

I've spent a while reading about GenericRelations but I'm still not exactly sure how to go about this. The Django documentation shows using GenericRelation fields on the models that my Permission points to, but it can point to many many different things and I'm hoping to get a way to use this functionality without putting a GenericRelation on every possible linked to model.

Thanks!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9160074b-4b1c-490b-93d9-d607895ba4eb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment