在Django admin中显示ManyToMany关系的两面 [英] Displaying both sides of a ManyToMany relationship in Django admin

查看:388
本文介绍了在Django admin中显示ManyToMany关系的两面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下具有多对多关系的模型:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆