在Django admin中显示ManyToMany关系的两面 [英] Displaying both sides of a ManyToMany relationship in Django admin
问题描述
说我有以下具有多对多关系的模型:
Say I have the following models that have a many-to-many relationship:
class Foo(models.Model):
name = models.TextField()
class Bar(models.Model):
name = models.TextField()
foos = models.ManyToManyField(Foo, related_name='bars')
,然后以以下方式在admin中定义它们:
And then having defined them in admin in the following way:
@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
"""Foo admin."""
list_display = ('name',)
search_fields = ('name',)
@admin.register(Bar)
class BarAdmin(admin.ModelAdmin):
"""Bar admin."""
list_display = ('name',)
search_fields = ('name',)
在Django管理员中,浏览<$ c $ c> Bar 实例,我可以看到 Foo
实例 Bar
已关联
In Django admin, when browsing Bar
instances, I can see the Foo
instances Bar
is associated with and can modify them from there.
但是, Foo
没有运气,我看不到每个Foo对象都关联的 Bar
实例。
However, no such luck with Foo
, I can't see the Bar
instances that every Foo object is associated with.
Django是否可以为此定义自动处理,否则我需要
Can Django define automatic handling for this or would I need to roll my own methond?
我正在使用Python 3.6.1和Django 1.11。
I'm using Python 3.6.1 and Django 1.11.
推荐答案
您可以这样定义自定义 InlineModelAdmin
:
You could define a custom InlineModelAdmin
like so:
class BarInline(admin.TabularInline):
model = Bar.foos.through
并在您的 FooAdmin
中使用:
class FooAdmin(admin.ModelAdmin):
"""Foo admin."""
model = Foo
inlines = [
BarInline,
]
看看django的这一部分文档。
Have a look at this part of the django documentation.
这篇关于在Django admin中显示ManyToMany关系的两面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!