以便每次调用request

以便每次调用request

本文介绍了如何在请求中缓存user.groups,以便每次调用request.user.groups.all()时都不会命中db?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Django与Django REST结合使用,并且具有基于用户组的用户权限系统。结果,我必须在视图中多次检查分配的用户组,以使用 request.user.groups.all()来查看用户是否属于某个组。它可以正常工作,但是每次这样的调用都会导致对数据库的额外查询以检索组。

I'm using Django with Django REST and have a user permission system based on user groups. As a result I have to check assigned user groups a few times inside views to see if a user belongs to a certain group using request.user.groups.all(). It works but every such call results in an extra query to db to retrieve groups.

我希望我可以重写一些在身份验证期间将用户从数据库中拉出的方法,然后再附加它可以添加到请求中,所以我可以添加类似

I wish I could override some method that pulls a user from a db during authentication before attaching it to a request, so I can add something like

User.objects.get(pk=userid).prefetch_related('groups')

因此,每当我访问更远的组时,都不会再打任何电话。

so no extra calls would be made whenever I access groups further down.

推荐答案

您应该能够利用Python的属性:

You should be able to take advantage of the Python's property:

class User(...):
    @property
    def cached_groups(self):
        if not hasattr(self, '_cached_groups'):
            self._cached_groups = list(self.groups.all())
        return self._cached_groups

因此,每当您使用user.cached_groups时,您都会命中一个缓存查询集,该查询集的持续时间将与您的用户实例的使用时间一样长。

therefore, whenever you use user.cached_groups you will hit a cached queryset that will only last as long as your user instance will.

这篇关于如何在请求中缓存user.groups,以便每次调用request.user.groups.all()时都不会命中db?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 04:21