如何将 filter_horizontal 与 TabularInline 和 .through 一起使用?

How to use filter_horizontal with TabularInline and .through?

我的模特是

class Test(models.Model):
    name = models.CharField(max_length=255)

class Testrelated(models.Model):
    name = models.CharField(max_length=255)
    tests = models.ManyToManyField(Test, related_name='tests')

和管理员:

class TestrelatedInline(admin.TabularInline):
    extra = 0
    model = models.Test.tests.through
    filter_horizontal = ('name')

class TestAdmin(admin.ModelAdmin):
    list_display = ('id', 'name')
    search_fields = ('name',)

    inlines = [
        TestrelatedInline,
    ]

问题是 .through 没有模型字段。所以我不能使用 filter_horizontal.

来引用任何字段
<class 'app.admin.TestrelatedInline'>: (admin.E019) The value of 'filter_horizontal[0]' refers to 'name', which is not an attribute of 'app.Testrelated_tests'.

我创建了一个测试台https://gitlab.com/marataziat/testdjangoproject

您的情况不需要内联管理员。 filter_horizontal 机制旨在通过其自己的管理页面中的多选小部件处理多对多关系。

如果您想使用表格内联并在需要时插入额外内容,您可以重写 TabularInline 的 formfield_for_foreignkey 来定义查询集和小部件。

class TestrelatedInline(admin.TabularInline):
    extra = 0
    model = models.Test.tests.through
    
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "testrelated":
            kwargs["queryset"] = models.Testrelated.objects.all()
            kwargs["widget"] = Select(attrs={"style": "width:400px"},)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)