当模型字段中的值不再满足 limit_choices_to 标准时保留它们

发布于 2024-09-17 11:26:51 字数 345 浏览 4 评论 0原文

我有一个与作者有外键关系的文章模型,需要使用 limit_choices_to 因为我在数据库中有超过 2,000 个可能的作者。问题是,当这些作者不再满足 limit_choices_to 标准(例如,他们变得不活跃)时,当我编辑旧文章时,他们会从作者字段中消失,因此我无法将他们保存为这些旧文章的作者。

如何使用 limit_choices_to 同时保留字段中的值,即使它会被 limit_choices_to 排除?

我尝试过自定义 save() 和 init,使用 clean() 重写原始值,甚至尝试使用自定义管理表单但没有成功。肯定有人遇到了这种困境,而我可能错过了一些简单的事情,但我被难住了。

I have an Article model that has a foreign key relationship with Author that needs to use a limit_choices_to because I have over 2,000 possible authors in the database. The problem is that when these authors no longer meet the limit_choices_to criteria (e.g. they become inactive), they disappear from the author field when I edit old articles and therefore I can't save them as the author on those old articles.

How do I use limit_choices_to while preserving the value in the field, even if it would otherwise be excluded by limit_choices_to?

I have tried customizing save() and init, rewriting the original value using clean(), and even tried to use a custom admin form without success. Surely someone has run into this dilemma and I'm probably missing something easy, but I'm stumped.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

牵强ㄟ 2024-09-24 11:26:51

我认为执行此操作的方法是在自定义表单的 init 中,您可以在其中动态修改“作者”字段的选择以包含当前作者。像(未经测试)的东西:

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

I think the way to do this would be in the init of a custom form, where you could dynamically modify the choices of the Author field to include the current author. Something like (untested):

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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文