0

I want to override the behaviour of objects.all() of a particular model based on information that is within the session and I dont know how to get the session data at that point

Thanks

EDIT Just a bit more of an explanation of what/why im doing this. We have a project but want to apply a filter to what the user can see according to what they are logged into. So its ok for it to affect how "all()" works. Our project has already been build and we are modifying it so we dont want to have to go through and change all the objects.all() and add in the request. Hope this clears things up

neolaser
  • 6,722
  • 18
  • 57
  • 90

1 Answers1

-2

You should make a method on a custom manager for that that:

from django.db import models

class MyManager(models.Manager):
    def all(self, session=None):
        if session is None:
            return self.all()
        else:
            return self.filter(.....)

class MyModel(models.Model):
    # fields go here
    objects = MyManager()

Though this is probably not the recommended approach, as it is changing the behaviour of all() which could have some unexpected effects on other parts of your app! Alternatively you could either add a NEW method to the manager for this purpose, or do some additional filtering in the view:

# code in the view
qs = MyModel.objects.all()
if session....:
    qs = qs.filter(...)

But you will always need to pass the necessary data to your filter method! Consider that the method might also be involed from a location that has no access to request/session data (eg. the shell), therefore a good architecture demands this!

Bernhard Vallant
  • 49,468
  • 20
  • 120
  • 148
  • I have edited the question now, We wanted to implement this so it worked invisibly, so we dont have to change some code already written. This may have to be our solution though! thanks for the answer – neolaser Jun 27 '11 at 00:14
  • 2
    This will go to a infinite recursion call, `all` calling `all`. – Gocht Sep 03 '15 at 21:18