7

我有以下模型类:

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

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

4

1 回答 1

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

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

admin.site.register(Book, BookAdmin)

文档

于 2012-05-31T11:43:03.140 回答