How can I enable inline ManyToManyFields on my Dja

2019-03-15 02:17发布

Let's say I have Books and Author models.

class Author(models.Model):
    name = CharField(max_length=100)

class Book(models.Model):
    title = CharField(max_length=250)
    authors = ManyToManyField(Author)

I want each Book to have multiple Authors, and on the Django admin site I want to be able to add multiple new authors to a book from its Edit page, in one go. I don't need to add Books to authors.

Is this possible? If so, what's the best and / or easiest way of accomplishing it?

3条回答
Melony?
2楼-- · 2019-03-15 02:25

Try this:

class AuthorInline(admin.TabularInline):

    model = Book.authors.through
    verbose_name = u"Author"
    verbose_name_plural = u"Authors"


class BookAdmin(admin.ModelAdmin):

    exclude = ("authors", )
    inlines = (
       AuthorInline,
    )

You might need to add raw_id_fields = ("author", ) to AuthorInline if you have many authors.

查看更多
Rolldiameter
3楼-- · 2019-03-15 02:36
爷、活的狠高调
4楼-- · 2019-03-15 02:44

It is quite simple to do what you want, If I am getting you correctly:

You should create an admin.py file inside your apps directory and then write the following code:

from django.contrib import admin
from myapps.models import Author, Book

class BookAdmin(admin.ModelAdmin):
     model= Book
     filter_horizontal = ('authors',) #If you don't specify this, you will get a multiple select widget.

admin.site.register(Author)
admin.site.register(Book, BookAdmin)
查看更多
登录 后发表回答