Skip to main content
 首页 » 编程设计

python之django admin many-to-many with intermediate model 添加新的

2025年02月15日54mate10pro

我有以下模型(简化):

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() 

基本上,歌曲可以在多场演唱会中,一场演唱会有多首歌曲。

在管理 View 中创建新音乐会时,我希望能够添加新歌曲。这是我拥有的:

class ConcertAdmin(admin.ModelAdmin): 
    ... 
    inlines = [SongInline] 
 
class SongInline(admin.TabularInline): 
    model = RunOrder 
    show_change_link = True 
    extra = 1 

但这只能让我从现有歌曲中进行选择。为了添加一首新歌,我必须使用歌曲管理界面。当我尝试使用 Song 作为 SongInline 的模型时,出现了 has no ForeignKey 错误。有没有一种方法可以简化/内联将新歌曲添加到 Concert 的过程?

请您参考如下方法:

事实证明这是默认功能,但必须为 Song 模型启用管理界面:

admin.site.register(Song) 

然后您会看到一个小加号。 Screenshot of django admin inline table .