【问题标题】:Is it right that django migrations are running the filter of django tables2 module before running the migrations?django 迁移在运行迁移之前运行 django tables2 模块的过滤器是否正确?
【发布时间】:2019-08-02 13:26:17
【问题描述】:

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

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

【问题讨论】:

    标签: python django django-migrations django-tables2


    【解决方案1】:

    system checks frameworkmakemigrationsmigrate 命令运行之前运行。

    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())
    

    【讨论】:

    • 只为您感兴趣:它有效!谢谢您的回答。对于 ModelChoiceFilter,它看起来如下:self.filters['practice_phase'].queryset = PracticePhase.objects.filter(pk__in=get_pp_for_specialpermit())
    • @DominicM。很高兴它奏效了。我已经用正确的代码更新了__init__ 方法。
    猜你喜欢
    • 2015-08-12
    • 2014-10-29
    • 2018-05-04
    • 2013-02-01
    • 2015-12-08
    • 2020-06-22
    • 2021-12-01
    • 2015-11-04
    • 1970-01-01
    相关资源
    最近更新 更多