我有一个半大型软件。有一次,我将table2包含在该项目中并开始使用它。我在filter.py文件中包含了一些基本的模型过滤。现在,如果我删除我的数据库并尝试运行新的迁移,我会收到错误,该表无法使用。我建立了一个尝试捕获并且它正在工作,因为它不会在迁移之前运行代码剪切。

class PracticephaseProjectFilter(django_filters.FilterSet):
    omni = django_filters.CharFilter(method=omni_search, label="Suche")
    practice_phase = django_filters.ModelChoiceFilter(queryset=PracticePhase.objects.filter(pk__in=get_pp_for_specialpermit()))

    class Meta:
        model = PracticePhaseProject
        fields = ['practice_phase']

    def __init__(self, *args, **kwargs):
        super(PracticephaseProjectFilter, self).__init__(*args, **kwargs)
def get_pp_for_specialpermit():
    pp = []
    today = date.today()
    # check if SS or WS required
    if 4 <= today.month <= 9:
        # current SS, project will be sought for WS this year
        pp_str = [str(today.year)[-2:] + "s", str(today.year - 1)[-2:] + "w"]
    # we are in WS, check correct year for SS
    elif today.month > 9:
       pp_str = [str(today.year)[-2:] + "w", str(today.year)[-2:] + "s"]
    # we are allready in the year of next SS
    else:
        pp_str = [str(today.year - 1)[-2:] + "s", str(today.year - 1)[-2:] + "w"]
    try:
        for _pp in PracticePhase.objects.filter(semester__name__in=pp_str):
            pp.append(_pp.pk)
    except:
        pass
    return pp

现在,如果我删除for循环的try catch,我就无法运行迁移,因为我遇到数据库错误,没有table practicephase。但是在迁移之前永远不应该调用该文件。

分析解答

系统检查框架makemigrationsmigrate命令运行之前运行。

URL检查会导致您的urls.py被导入,从而加载包含PracticephaseProjectFilter的module。

您不应该在filterset定义中调用get_pp_for_specialpermit - 这意味着查询将在服务器启动时运行一次。这意味着在Django服务器准备就绪之前,您有一个不必要的查询,结果可能会在以后失效。

您可以通过将查询集移动到__init__方法来阻止查询运行:

class PracticephaseProjectFilter(django_filters.FilterSet):
    omni = django_filters.CharFilter(method=omni_search, label="Suche")
    practice_phase = django_filters.ModelChoiceFilter(queryset=PracticePhase.objects.none())

    class Meta:
        model = PracticePhaseProject
        fields = ['practice_phase']

    def __init__(self, *args, **kwargs):
        super(PracticephaseProjectFilter, self).__init__(*args, **kwargs)
        self.filters['practice_phase'].queryset = PracticePhase.objects.filter(pk__in=get_pp_for_specialpermit())