Search code examples
djangodjango-adminmodeladmin

Django admin: how do I add an unrelated model field to a model change/add page?


I have the following models:

class Foo(models.Model):
    field1 = models.IntegerField()
    ...

class Bar(models.Model):
    field1 = models.IntegerField()
    ...

class Foo_bar(models.Model):
    foo = models.ForeignKey(Foo)
    bar = models.ForeignKey(Bar)
    ...

In the admin, I want it so that in the Foo change/add page, you can specify a Bar object, and on save I want to create a Foo_bar object to represent the relationship. How can I do this through customizing the Admin site/ModelAdmins? Note that inlining isn't quite what I need because there is no explicit foreign key relationship between foo and bar. And second, I don't actually want to edit bar objects, I just want to choose from amongst the ones that are in the system.

Thanks.


Solution

  • Are you sure you don't just want a ManyToManyField? In the admin, this would manifest as a multiple-selection list of Bar objects. Look at the group selection part of the admin for User.

    If you need additional data attached to the relationship, you could use a through parameter:

    class Foo(models.Model):
        field1 = models.IntegerField()
        bars = models.ManyToManyField("Bar", related_name="foos", through="Foo_bar")
    

    You'll need to add Foo_bar to the admin in order to edit these additional parameters in the admin.