Reputation: 47
I want to make some user information available to two different functions in my view.py. But, I want to hit database only once, not twice. Is there a way I can do this?
Here is the function that outputs some user info (userlocs):
def get_user_info(profile_ins):
fav_loc = list()
lat = list()
lon = list()
for loc in UserLoc.objects.filter(profile=profile_ins):
fav_loc.append(loc.name)
lat.append(loc.location.geo_code_lat)
lon.append(loc.location.geo_code_lon)
userlocs = list(zip(fav_loc, lat, lon))
return userlocs
This is the view function when user looks at his profile. This is where I first call get_user_info:
def profile(request):
profile_instance = Profile.objects.get(user=request.user)
userlocs = get_user_info(profile_instance)
context = {'locations': userlocs}
return render(request, 'profile.html', context)
Now, I want the userloc list to be available to the following function too. This function is supposed to compare user input to the existing userloc info. I know I can again call get_user_info function, but I think this is redundant, as I already called it once.
def add_location_exe(request):
if request.method == 'POST':
ln = UserLocForm(request.POST or None)
if ln.is_valid():
name = ln.cleaned_data.get("name")
## is name in userloc list ##
Thanks for your help.
Upvotes: 0
Views: 183
Reputation: 73470
You are talking about two view functions that are supposed to access the same global variable. This is not a good idea for more than one reason:
The content of userloc
depends on the state of the database. Since you only call one view per request, the data might have changed.
You have no guarantee that the two requests are even handled by the same Python process. Hence, there is no such thing as a global variable that can be set and persisted across requests.
For both those reasons, real global variables (the ones that do not change; not database records!) should be kept in the settings. If you want to limit database accesses in a complex application during one request-response cycle, you can use the cached_property
decorator:
class Foo(object):
def __init__(self, profile_ins):
self.profile_ins = profile_ins
@cached_property
def get_user_info(self):
return ...
# views.py
# ...
foo = Foo()
This will cache the value of foo.get_user_info
for the entire cycle.
Upvotes: 3