How to cache user.groups in a request so db isn't hit every time you call request.user.groups.all()?

和自甴很熟 提交于 2019-12-11 03:53:01

问题


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.


回答1:


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

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



来源:https://stackoverflow.com/questions/43236677/how-to-cache-user-groups-in-a-request-so-db-isnt-hit-every-time-you-call-reques

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!