Display m2m field defined via 'through' in admin

廉价感情. 提交于 2019-12-20 23:26:05

问题


I have the following model classes:

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)

When adding a new book object in admin interface I would like to also add a new category, and book_category relationship.

If I include categories in BookAdmin as

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

I get can't include the ManyToManyField field 'categories' because 'categories' manually specifies a 'through' model error.

Is there any way to achieve required functionality?


回答1:


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

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

admin.site.register(Book, BookAdmin)

Docs



来源:https://stackoverflow.com/questions/10832767/display-m2m-field-defined-via-through-in-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!