在admin中显示通过'through'定义的m2m字段

时间:2012-05-31 11:34:00

标签: django admin models m2m

我有以下模型类:

class Category(models.Model):
    category = models.CharField('category', max_length=200, blank=False)

class Book(models.Model):
    title = models.CharField('title', max_length=200, blank=False)
    categories = models.ManyToManyField(Category, blank=False, through='Book_Category')

class Book_Category(models.Model):
    book = models.ForeignKey(Book)
    category = models.ForeignKey(Category)

在管理界面中添加新书对象时,我还想添加一个新类别和book_category关系。

如果我在BookAdmin中包含类别

class BookAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['categories', ]}), ...

我收到can't include the ManyToManyField field 'categories' because 'categories' manually specifies a 'through' model错误。

有没有办法实现所需的功能?

1 个答案:

答案 0 :(得分:13)

class CategoryInline(admin.TabularInline):
    model = Book_Category
    extra = 3 # choose any number

class BookAdmin(admin.ModelAdmin):
    inlines = (CategoryInline,)

admin.site.register(Book, BookAdmin)

Docs