Force sending a user to custom QuerySet.

Posted by Jack M. on Stack Overflow See other posts from Stack Overflow or by Jack M.
Published on 2010-04-09T17:33:04Z Indexed on 2010/04/09 18:13 UTC
Read the original article Hit count: 272

Filed under:
|

I'm trying to secure an application so that users can only see objects which are assigned to them. I've got a custom QuerySet which works for this, but I'm trying to find a way to force the use of this additional functionality. Here is my Model:

class Inquiry(models.Model):   
    ts = models.DateTimeField(auto_now_add=True)
    assigned_to_user = models.ForeignKey(User,
            blank=True,
            null=True,
            related_name="assigned_inquiries")
    objects = CustomQuerySetManager()
    class QuerySet(QuerySet):
        def for_user(self, user):       
            return self.filter(assigned_to_user=user)

(The CustomQuerySetManager is documented over here, if it is important.)

I'm trying to force everything to use this filtering, so that other methods will raise an exception. For example:

Inquiry.objects.all() ## Should raise an exception.
Inquiry.objects.filter(pk=69) ## Should raise an exception.
Inquiry.objects.for_user(request.user).filter(pk=69) ## Should work.
inqs = Inquiry.objects.for_user(request.user) ## Should work.
inqs.filter(pk=69) ## Should work.

It seems to me that there should be a way to force the security of these objects by allowing only certain users to access them.

I am not concerned with how this might impact the admin interface.

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models