这是我的模型关系(摘自Django 2.1官方文档-我的模型是该模型的精确副本,但只有模型名称不同。):
class Person(models.Model):
name = models.CharField(max_length=50)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(
Person,
through='Membership',
through_fields=('group', 'person'),
)
class Membership(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
这是我的admin.py:
class MembershipInLine(admin.StackedInline):
model = Membership
class PersonAdmin(admin.ModelAdmin):
inlines = [
MembershipInLine,
]
我在“人员”页面上得到如下字段: Current view
但是我想拥有这种风格: Desired view
我在official documentation中找到了filter_horizontal
和filter_vertical
,但是我不知道如何将它们与内联一起使用。我该怎么办?
编辑:
我已经按照文档中所述进行了尝试:
class MembershipInLine(admin.StackedInline):
model = Membership # (and also tried with = Group.members.through)
filter_horizontal = ('group', )
但是它抛出:
(admin.E020)“ filter_horizontal [0]”的值必须是“多对多”字段。
答案 0 :(得分:0)
有关组的权限,请咨询auth admin面板。尝试类似
class PersonAdmin(admin.ModelAdmin):
search_fields = ()
ordering = ()
filter_horizontal = ('membership',)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if db_field.name == 'membership':
qs = kwargs.get('queryset', db_field.remote_field.model.objects)
# Avoid a major performance hit resolving membership names which
# triggers a content_type load:
kwargs['queryset'] = qs.select_related('content_type')
return super().formfield_for_manytomany(db_field, request=request, **kwargs)
https://github.com/django/django/blob/master/django/contrib/auth/admin.py#L29