如何在我的Django管理站点上启用内联ManyToManyFields?

时间:2022-05-16 07:23:09

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.

我希望每本书都有多个作者,在Django管理网站上,我希望能够一次性从编辑页面中将多个新作者添加到一本书中。我不需要为作者添加书籍。

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

这可能吗?如果是这样,最好和/或最简单的方法是什么?

3 个解决方案

#1


19  

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:

您应该在apps目录中创建一个admin.py文件,然后编写以下代码:

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)

#2


12  

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.

如果您有许多作者,则可能需要将raw_id_fields =(“author”,)添加到AuthorInline。

#3


6  

Well, check out the Django docs on many to many usage with inlines.

那么,请查看Django文档,了解有关内联的多种用法。

#1


19  

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:

您应该在apps目录中创建一个admin.py文件,然后编写以下代码:

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)

#2


12  

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.

如果您有许多作者,则可能需要将raw_id_fields =(“author”,)添加到AuthorInline。

#3


6  

Well, check out the Django docs on many to many usage with inlines.

那么,请查看Django文档,了解有关内联的多种用法。