How do I properly cache an object (not a model) in Django?

  • 0
    Good afternoon!

    There is a PaymentChecker class, its creation takes quite a long time, and it is not profitable to create it in each request, since it does not change from request to request, that is, you need something like a singleton. Therefore, the actual question is how to cache it correctly or organize it as a singleton.

    It would be correct to put it in a separate file, for example of the following form:

    class PaymentChecker(object):
    payment_checker = PaymentChecker(<some constant args>)
    import utils
    class CheckPayment(View):
        def get(...):
               if utils.payment_checker.check(...):

    Thank you in advance :-)
    Django Anonymous, Dec 27, 2019

  • 1 Answers
  • 0
    If at the compilation stage there is enough data to create, this is possible.

    Another option is to make a lazy getter, something like
    _payment_checker = None
    def get_payment_checker():
    global _payment_checker
    if _payment_checker is None:
    _payment_checker = PaymentChecker(<some constant args>)
    return _payment_checker

    or the same through the static class method
    class PaymentChecker(object):
    __instance = None
    def get_checker(cls):
    if cls.__instance is None:
    cls.__instance = cls(<some constant args>)
    return cls.__instance

    the second option is preferable - it's easier to develop :)

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!