Andrew Hartnett
Andrew Hartnett

Reputation: 33

django admin many-to-many with intermediate model add new

I have the following models (simplified):

class Concert(models.Model):
    title = models.CharField(max_length=50) 
    date = models.DateField()
    songs = models.ManyToManyField(Song,
                                   through='RunOrder',
                                   related_name='run_order',
                                   blank=True)

class Song(models.Model):
    title = models.CharField(max_length=50)


class RunOrder(models.Model):
    concert = models.ForeignKey(Concert, on_delete=models.CASCADE)
    song = models.ForeignKey(Song, on_delete=models.CASCADE)
    act_no = models.SmallIntegerField()
    scene_no = models.SmallIntegerField()

Basically, songs can be in multiple concerts, concerts have multiple songs.

While creating a new concert in the admin view, I would like to be able to add new songs. Here's what I have:

class ConcertAdmin(admin.ModelAdmin):
    ...
    inlines = [SongInline]

class SongInline(admin.TabularInline):
    model = RunOrder
    show_change_link = True
    extra = 1

But this only lets me select from existing songs. In order to add a new song, I have to use the Song admin interface. When I tried to use Song as the model for SongInline, I got a has no ForeignKey error. Is there a way I can streamline/inline the process of adding new Songs to a Concert?

Upvotes: 2

Views: 631

Answers (1)

Andrew Hartnett
Andrew Hartnett

Reputation: 33

It turns out this is a default feature, but the admin interface has to be enabled for the Song model:

admin.site.register(Song)

Then you get the little plus sign. Screenshot of django admin inline table.

Upvotes: 1

Related Questions