如何在我的 Django 管理站点上启用内联 ManyToManyFields? [英] How can I enable inline ManyToManyFields on my Django admin site?
问题描述
假设我有 Books 和 Author 模型.
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)
我希望每本书都有多个作者,并且在 Django 管理站点上,我希望能够从其编辑页面一次性将多个新作者添加到一本书中.我不需要向作者添加图书.
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?
推荐答案
做你想做的事情很简单,如果我没看错的话:
It is quite simple to do what you want, If I am getting you correctly:
您应该在您的应用程序目录中创建一个 admin.py 文件,然后编写以下代码:
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)
这篇关于如何在我的 Django 管理站点上启用内联 ManyToManyFields?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!