代码之家  ›  专栏  ›  技术社区  ›  Jamie

当模型字段不再满足限制条件时,保留这些字段中的值

  •  0
  • Jamie  · 技术社区  · 14 年前

    如何在保留字段中的值的同时使用limit\u choices\u to,即使它会被limit\u choices\u to排除?

    我尝试过自定义save()和 ,使用clean()重写原始值,甚至尝试使用自定义管理窗体都没有成功。肯定有人陷入了这种困境,我可能错过了一些简单的东西,但我被难住了。

    1 回复  |  直到 14 年前
        1
  •  1
  •   Daniel Roseman    14 年前

    我认为这样做的方法是 在自定义窗体中,可以动态修改 choices 要包括当前作者的作者字段。类似(未经测试):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        current_author_id = self.instance.author_id
        self.fields['author'].queryset = Author.objects.filter(Q(is_active=True) | 
                                                             Q(pk=current_author_id))