Skip to main content
 首页 » 编程设计

python之在运行迁移之前,django 迁移是否正在运行 django tables2 模块的过滤器

2024年09月03日28daizhj

我有一个半大型软件。有一次我将 tables2 包含到该项目中并开始使用它。我在 filter.py 文件中包含了一些基本的模型过滤。现在,如果我删除我的数据库并尝试运行新的迁移,我会收到错误消息,即该表不可用。我构建了一个 try catch around 并且它正在工作,因为它不运行迁移之前截断的代码。

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,我将无法运行迁移,因为我遇到数据库错误,即没有表练习阶段。但在迁移之前不应调用该文件。

请您参考如下方法:

system checks framework在 makemigrations 和 migrate 命令运行之前运行。

URL 检查会导致您的 urls.py 被导入,它会加载包含 PracticephaseProjectFilter 的模块。

您不应该在过滤器集定义中调用 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())