Django admin - 将多对多字段的选择限制为已选择的对象

问题描述

我有一个包含多对多字段的模型,我想将 django 管理详细信息视图中的选项限制为已选择的选项,并允许添加新的选项。我尝试了以下方法

# models.py
class Document(models.Model):
    ...
    followups = models.ManyToManyField(
        Followup,blank=True,)
    ...
# admin.py
...
class DocumentAdminForm(ModelForm):
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields["followups"].queryset = kwargs["instance"].followups.all()


class DocumentAdmin(admin.ModelAdmin):
    form = DocumentAdminForm
...

过滤器对已选择的对象按预期工作,但是当我尝试添加新对象或删除一个对象时出现以下错误Select a valid choice. <OBJECT ID> is not one of the available choices.

我是否遗漏了表单中的某些内容,或者我是否需要以其他方式执行此操作。我想到了模型中的 limit_choice_to,但不知道如何为这种情况获得正确的过滤器。

我使用的是 django 3.1

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)