显示M2M场通过在管理员定义的“到”(Display m2m field defined via &

2019-07-29 16:02发布

我有以下的模型类:

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误差。

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

Answer 1:

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

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

admin.site.register(Book, BookAdmin)

文件



文章来源: Display m2m field defined via 'through' in admin