Question

When I get a list of objects I only ever want to the objects that belong to the logged in user.

I'm thinking, maybe this can be done in the model manager by overriding the default manager, but I'm unsure how to get the logged in use. This is what I have so far...

class GroupsManager(models.Manager):
    def get_query_set(self):
        return super(GroupsManager, self).get_query_set().filter(user=???????)

I'm I on the right track? How can I achieve my goal? Or is there a better way to do this?

Thanks.

Was it helpful?

Solution

You don't have access to the request (and therefore the currently logged in user) in the model or model manager. So you could write a generic manager method that accepts a user instance and only returns objects belonging to that user:

class GroupsManager(models.Manager):
    def for_user(self, user):
        return self.get_query_set().filter(user=user)

and in your model:

class Group(models.Model):
    objects = GroupsManager()

and in the view:

def my_view(request):
    groups = Group.objects.for_user(request.user)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top