[Fixed]-Displaying both sides of a ManyToMany relationship in Django admin

24👍

You could define a custom InlineModelAdmin like so:

class BarInline(admin.TabularInline):
    model = Bar.foos.through

and use it in your FooAdmin:

class FooAdmin(admin.ModelAdmin):
"""Foo admin."""
    model = Foo
    inlines = [
        BarInline,
    ]

Have a look at this part of the django documentation.

👤Hopiu

4👍

You can define custom fields for list_display like this:

@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
    """Foo admin."""

    list_display = ('name', 'get_bars')
    search_fields = ('name',)

    def get_bars(self, obj):
        return obj.bars.all()

This is a very simple example, but I hope it can help you as a starting point.

EDIT:

You can display the associated objects in the edit form as readonly:

readonly_fields = ('get_bars',)
fields = ('name', 'get_bars')
👤cezar

1👍

This code below can display both Foo and Bar models in many-to-many relationship on the same page in Django Admin:

class BarInline(admin.TabularInline):
    model = Bar.foos.through

@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
    inlines = (BarInline,)

Be careful, if using model = Bar instead of model = Bar.foos.through in many-to-many relationship as shown below:

class BarInline(admin.TabularInline):
    # model = Bar.foos.through
    model = Bar # This will get error

@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
    inlines = (BarInline,)

You will get the error below:

ERRORS: <class ‘xxx.admin.BarInline’>: (admin.E202)
‘xxx.Bar’ has no ForeignKey to ‘xxx.Foo’.

0👍

There is a module called django-admin-extend which provides a generic mechanism to define “Bidirectional many to many fields”. I’m not sure if it still works, because the last contribution is two years old, bit it should be worth giving it a try.

Leave a comment