On Jun 23, 8:28 pm, derek <gamesb...@gmail.com> wrote:
> I would like to define a default manager for MyModel that always
> filters all records (when the model is accessed from anywhere in my
> application) based on data from the request:
>
> e.g. on the lines of:
>
> class MyModelManager(models.Manager):
>     #override default
>     def get_query_set(self, request):
>         if request.foo == bar:
>             return super(MyModelManager, self).get_query_set()
>         return MyModel.objects.filter(spam = eggs)
>
> class MyModel(models.Model):
>     ...
>     objects = MyModelManager()
>
> However I get the error:
>
> Django Version: 1.2.1
> Exception Type: TypeError
> Exception Value:
> Error when calling the metaclass bases
>     get_query_set() takes exactly 2 arguments (1 given)
>
> So its clear that get_query_set() cannot take the request inserted
> there... but how else can I access the request inside the above model
> Manager class?
>
> (Note that I don't want to define an extra method that needs to be
> appended onto the MyModels.objects.zzz type of chained calls  - such
> as the solution posted 
> athttp://osdir.com/ml/django-users/2010-02/msg00819.html
> - as I would then have to make these changes throughout the
> application, and also remember to add such a method to all future
> code.)

Well, I had to get something up-and-running, so I have fallen back on
the "don't try this in your app" method of threads.

I implemented this based on this blog entry:

http://chewpichai.blogspot.com/2007/09/using-user-info-outside-request-in.html

to get the "threadlocals" created.

and then in "modelmanagers.py", I have:

from myapp.middleware import threadlocals

def get_user():
    return threadlocals.get_current_user()

class MyModelManager(models.Manager):
    def get_query_set(self):
        user = get_user()
        if user == None or user.is_superuser:
            return super(MyModelManager, self).get_query_set()
        return super(MyModelManager,
self).get_query_set().filter(created_by = user)

I _know_ this is not the "technically correct" way to do this, and
would be very happy if someone pointed out how to rewrite the
get_user() function to something more acceptable.

Thanks
Derek

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to