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

发布于 2024-10-15 12:26:34 字数 331 浏览 2 评论 0原文

假设我有书籍和作者模型。

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

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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

奢华的一滴泪 2024-10-22 12:26:34

做你想做的事情非常简单,如果我没理解错的话:

你应该在 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)

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)
dawn曙光 2024-10-22 12:26:34

试试这个:

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,
    )

如果您有很多作者,您可能需要将 raw_id_fields = ("author", ) 添加到 AuthorInline 中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文