Django View Class retains values

0

A curiosity that has been with me for a long time in Django and I never managed to heal:

Next. Let's say I have something like:

from django.shortcuts import render
from django.views import View

from pagina.models import Config

class BasicView(View):
  try:
    dados = {
      'email': Config.objects.get(variavel = 'email').valor,
    }
  except:
    dados = {}

class TelaView(BasicView):
  def get(self, request, **kwargs):
    self.template_name = 'base.html'
    return render(request, self.template_name, self.dados)

Then, in the base.html template, I would call {{email}} and django would show the database in the database.

Now, if I kept the server running and modified the e-mail record in the database, for the new e-mail to appear in the template, it would be necessary to stop the server and run it again.

My question: Why does this happen and how do I get around this?

    
asked by anonymous 28.03.2018 / 12:29

1 answer

0

This is because when python will execute a script it creates a sort of cache of the files involved (those tralala.pyc files or the files that are inside the __pycache__ directory). Therefore, it performs the import of information between files only once (when it is executed), not every time the view is called.

This is a default behavior of the language itself, if you need to provide this information dynamically (it will change from time to time), look for a way to store it in the database through an object and use some queryset to fetch the same.

If you help, here has the documentation on querysets and here documentation on databases. If it was not entirely clear, I hope I have at least helped.

    
30.03.2018 / 02:45