开发者

Override djangos's object.all() with the request data

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 w开发者_运维问答hat 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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜