用请求数据覆盖djangos的object.all() [英] Override djangos's object.all() with the request data

查看:641
本文介绍了用请求数据覆盖djangos的object.all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据会话内的信息覆盖特定模型的 objects.all()的行为,我不知道如何获取会话数据在这一点上

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

感谢

编辑
只是一点点的解释为什么/为什么这样做。我们有一个项目,但是想要根据用户登录的内容应用过滤器。所以它的确可以影响all()的工作原理。我们的项目已经建立,我们正在修改它,所以我们不需要经过并更改所有的 objects.all()并添加到请求中。希望这样清除东西

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

推荐答案

您应该在自定义管理器上创建一个方法:

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()

虽然这可能不是推荐的方法,因为它正在改变 all()的行为,这可能对应用程序的其他部分有一些意想不到的影响!
或者您可以为此目的向经理添加一个新方法,或在视图中执行一些其他过滤:

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(...)

但是,您将始终需要将必要的数据传递给您的过滤器方法!考虑到该方法也可能来自于无法访问请求/会话数据(例如shell)的位置,因此良好的架构需要此功能!

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!

这篇关于用请求数据覆盖djangos的object.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆