Created
October 22, 2018 23:34
-
-
Save jaddison/ae26c2a654f59227562d6f5eae3eaf04 to your computer and use it in GitHub Desktop.
settings_singleton_model_example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# models.py | |
# the dev adds new fields to this as the client asks for more features | |
class ClientSettings(models.Model): | |
base_labour_rate = models.FloatField(...) | |
# middleware.py | |
class ClientSettingsMiddleware(object): | |
_settings = None | |
def __init__(self, get_response): | |
self.get_response = get_response | |
def __call__(self, request): | |
if not self._settings: | |
# there should only ever be a single ClientSettings instance/record | |
# in the DB; cache it in this middleware to prevent unnecessary DB | |
# lookups | |
self._settings = ClientSettings.objects.order_by('pk').first() | |
# set the settings on `request` so it's accessible from everywhere; | |
# in views, etc where ever `request` is passed | |
setattr(request, 'client_settings', self._settings) | |
response = self.get_response(request) | |
# set it up so that if the user changes the settings via | |
# admin, it sets a response attribute to cause this middleware | |
# to reload it's cached settings attribute | |
if getattr(response, 'reload_client_settings', False): | |
self._settings = None | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment