如何限制 ForeignKey/ManyToMany Wagtail ModelAdmin 字段中显示的项目?

How to limit what items are displayed in the ForeignKey/ManyToMany Wagtail ModelAdmin fields?

我想在 Wagtail 管理中限制 ManyToManyField 中显示的用户数量。

ModelAdmindjango 版本中,实现以下内容就足够了:

def partner_users_queryset(queryset, field, request):
    user = request.user
    if queryset and field == "users":
        return queryset.filter(groups__pk__in=user.groups.all())
    return queryset

@django_admin.register(Partner)
class PartnerAdmin(django_admin.ModelAdmin):
    ...
    def get_field_queryset(self, db, db_field, request):
        queryset = super().get_field_queryset(db, db_field, request)
        return partner_users_queryset(queryset, db_field.name, request)

Wagtail 中有没有办法限制 ManyToManyField 中显示的值?

目前似乎没有直接的方法可以在 wagtail 中执行相同的操作。一些等效的代码如下所示:

from wagtail.contrib.modeladmin.options import ModelAdmin
from wagtail.contrib.modeladmin.views import CreateView, EditView

class ModelFormMixin:
    def get_form(self):
        form = super().get_form()
        return self.model_admin.custom_model_form(self, form)

class ModelFormCreateView(ModelFormMixin, CreateView):
    pass

class ModelFormEditView(ModelFormMixin, EditView):
    pass

class ModelFormModelAdmin(ModelAdmin):
    create_view_class = ModelFormCreateView
    edit_view_class = ModelFormEditView

    def custom_model_form(self, view_instance, form):
        return form

class PartnerAdmin(ModelFormModelAdmin):
    ...
    def custom_model_form(self, view_instance, form):
        if not isinstance(view_instance, (ModelFormCreateView, ModelFormEditView)):
            return form
        user = view_instance.request.user
        queryset = form.fields["users"].queryset
        form.fields["users"].queryset = queryset.filter(groups__pk__in=user.groups.all())
        return form