本文介绍了如何在Django管理网站上启用内联ManyToManyFields?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有书籍和作者模型。

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:

您应该在apps目录中创建一个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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 05:43