在 Django forms.ModelChoiceField HOWTO 中限制显示的选择,但在清理期间设置受限制的值之一

发布于 2024-11-19 07:34:50 字数 271 浏览 7 评论 0原文

我有一个自定义字段,它是 ModelMultipleChoiceField 的子类。我提供了通过查询集参数显示的选项。此查询集排除某些值。当我在某些工作流程的清理操作期间需要选择一个最初通过查询集排除的选项时,我的问题就出现了。当我尝试保存这个值时,django 拒绝保存它,说它不是一个有效的选项。在查找 ModelMultipleChoiceField 的 clean 方法时,我发现它检查提供的“值”是否来自初始查询集中,这导致了我的困境。

我想知道是否有可能在不进行任何重大黑客攻击的情况下绕过这个问题。

I have a custom field which subclasses ModelMultipleChoiceField. I provide the choices to be displayed via queryset parameter. This queryset excludes certain values. My problem comes when during cleanup operation for some workflows I need to select an option which was initially excluded by the way of queryset. When I try to save this value django refuses to save it saying that it is not a valid option. On looking up the clean method for ModelMultipleChoiceField I found that it checks if the provided "value" is from within the initial queryset, which causes my dilemma.

I wanted to know if it is possible to circumvent this problem without any major hacks.

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

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

发布评论

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

评论(1

你穿错了嫁妆 2024-11-26 07:34:50

django/forms/models.py:1011 有这样的内容:

qs = self.queryset.filter(**{'%s__in' % key: value})

所以看来,如果您在调用 super(MyField, self).clean(value),您可以相对干净地处理这种边缘情况。

django/forms/models.py:1011 has this:

qs = self.queryset.filter(**{'%s__in' % key: value})

So it seems that if you overrode your custom field's clean() method to modify self.queryset as necessary before calling super(MyField, self).clean(value), you could handle this edge case relatively cleanly.

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