Display m2m field defined via 'through' in admin
Asked Answered
W

2

7

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?

Woald answered 31/5, 2012 at 11:33 Comment(0)
A
14
class CategoryInline(admin.TabularInline):
    model = Book_Category
    extra = 3 # choose any number

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

admin.site.register(Book, BookAdmin)

Docs

Andreasandree answered 31/5, 2012 at 11:43 Comment(0)
C
0

It's better to change the model rather than to use "Inline":

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

    class Meta:
        db_table = 'category'

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

    class Meta:
        db_table = 'book'

As a result, you will still get the many-to-many table "book_categories", but you will also be able to use "fieldsets" and "filter_horizontal".

Comedienne answered 12/6, 2024 at 12:30 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.