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 mul开发者_StackOverflow社区tiple 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:
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)
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.
Well, check out the Django docs on many to many usage with inlines.
精彩评论