Django Admin中多对多的反向内联

jckbn6z7  于 2023-01-18  发布在  Go
关注(0)|答案(1)|浏览(125)

如果之前有人问过这个问题,而我的搜索没有找到解决方案,我很抱歉。我希望包括两个模型的管理内联。Django版本是4.1.4

class Book(models.Model):
    title = models.CharField(max_length=100)
    author_series = models.CharField(max_length=100, blank=True, null=True)
    series = models.ManyToManyField(Series)
    ...

    def __str__(self):
        return self.title + " (" + str(self.pk) + ")"

class Series(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)
    category = models.CharField(max_length=50)
    publisher = models.CharField(max_length=100,blank=True, null=True)
    ...

    def __str__(self):
        return self.publisher + " " + self.name

我能够使用Model.field.through格式成功地完成转发关系:

class SeriesInline(admin.TabularInline):
    model = Book.series.through
    
class BookAdmin(admin.ModelAdmin):
    inlines = [SeriesInline,]

但也希望相反。

class InlineSeriesBooks(admin.TabularInline):
    model = Book.series_set.through
    ... Remainder is commented out ...

class SeriesAdmin(admin.ModelAdmin):
    list_display = ['name', 'category', 'publisher', 'link', 'created', 'modified']
    fields = ['name', 'category', 'publisher', 'link', 'created', 'modified']
    readonly_fields = ["created", "modified"]
    inlines = [InlineSeriesBooks,]

所有的链接似乎都是通过Django Admin, accessing reverse many to many这样的解决方案来建议前者,但拼写正确后会陷入循环。如果我删除内联语句,页面将加载。
先谢了。

c3frrgcw

c3frrgcw1#

这是等价的,因为两者都引用“隐藏”模型,所以:

class BookSeriesInline(admin.TabularInline):
    model = Book.series.through
    

class BookAdmin(admin.ModelAdmin):
    inlines = [BookSeriesInline,]
    

class SeriesAdmin(admin.ModelAdmin):
    inlines = [BookSeriesInline,]

因此,您可以为两个管理员使用相同的内联表,它是两个模型之间的连接表。

相关问题