问题
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