'Django model manager queryset not updating until server restarts

I have a program that lets users upload data files and lookup tables (both which are ID'd to a specific company) and map them together. One page lets users choose which company they want to map data for by looking at which companies have both data files and lookup tables, which I use a queryset/model manager for. The problem is if I load a new data file and hierarchy the queryset doesn't pick them up until the server restarts. The queryset returns all the companies that have a data file and hierarchies at the time the server starts, but not anything that's added afterwards. I think this must be because the queryset is defined at startup, but I'm not sure. Is there a way to work around this?

forms.py

class CompanySelectionForm(forms.Form):
    companies = RawData.objects.get_companyNames(source="inRDandH")
    companiesTuple = makeTuple(companies)
    print(companiesTuple)
    company = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-select'}), choices=companiesTuple)

managers.py

class RawDataManager(models.Manager):
    
    def get_queryset(self):
        return RawDataQuerySet(self.model, using=self._db)

    def get_companyNames(self, source):
        return self.get_queryset().get_companyNames(source)

class RawDataQuerySet(models.QuerySet):

    def get_companyNames(self, source):
        if (source == 'inRDandH'):
            distinct_companiesRD = self.filter(fileType=0).values_list('companyName', flat=True).distinct()
            distinct_companiesH = self.filter(fileType=1).values_list('companyName', flat=True).distinct()
            distinct_companies = set(distinct_companiesRD).intersection(set(distinct_companiesH))
        else:
            distinct_companies = self.values_list('companyName', flat=True).distinct()

        return distinct_companies


Solution 1:[1]

The problem is that this code runs only once, when the code is initialised on server start, because it is part of your form class definition:

companies = RawData.objects.get_companyNames(source="inRDandH")

The solution is to make choices a callable, which is run every time the form is instantiated. define that field dynamically, in the __init__ method of the form:

def get_companies_tuple():
    companies = RawData.objects.get_companyNames(source="inRDandH")
    return makeTuple(companies)


class CompanySelectionForm(forms.Form): 
    company = forms.ChoiceField(
        widget=forms.Select(attrs={'class': 'form-select'}), 
        choices=get_companies_tuple
    )     

This will now fetch the data from the database every time the form is initialised, rather than only once during startup.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1