2012-05-31 120 views
7

定義「到」我有以下的模型類:顯示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錯誤。

有什麼方法可以實現所需的功能嗎?

回答

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