Search for and add reverse foreign-keys

Hello, I’ve got two models in a many-to-many relationship. One is a Node, which can have many different Buildings, and one is a Building, which can have many different nodes.

Buildings hold the Field for Nodes. On the Add page and Change page, I can use filter_horizontal to search for and add nodes to a Building:

However, I am unable to do this in reverse, from the Node. I have a (somewhat customized) Inline which lets me view building details, but I’d like to achieve the above on the Node object so that I can go the other way.

Anyone know how to do this? Thanks in advance! :smiley:

The Django admin docs for working with many-to-many models covers this case of using an inline admin on both sides of a many-to-many relationship.

Side note: In the future, please post the actual code being discussed here instead of links to external repositories. When you do so, copy/paste the code into the body of your post, between lines of three backtick - ` characters. This means you’ll have a line of ```, then the code, then another line of ```. (This forces the forum software to keep your code properly formatted.)

Ah sorry about that, will do better in the future.

That’s just about what I want, thanks! Is there a way to use a filter_horizontal to select a building? The dropdown has >10k entries :sweat_smile:

Here’s what I’ve got right now:

class MembershipInline(admin.TabularInline):
    model = Building.nodes.through
    extra = 0

I don’t know from direct experience, but the docs at The Django admin site | Django documentation | Django certainly give me the impression you ought to be able to.

Haha! Success!

I actually needed to add an autocomplete_fields! I’m sure I could configure this to use filter_horizontal as well, but now I might try to combine this widget with another one to save some space :wink:

Here’s what worked.

class MembershipInline(admin.TabularInline):
    model = Building.nodes.through
    extra = 0
    autocomplete_fields = ["building_id"]