About Reverse M2M Relations in Administration
If a Book
has a ManyToManyField
pointing to Author
, then you can get a M2M selection of books at the author administration with a custom form:
# books/admin.py
from django.contrib import admin
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.utils.translation import gettext_lazy as _
from django import forms
from .models import Author, Book
class AuthorForm(forms.ModelForm):
books = forms.ModelMultipleChoiceField(
Book.objects.all(),
widget=FilteredSelectMultiple(_("Books"), False),
required=False,
)
class Meta:
model = Author
fields = "__all__"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.pk:
self.initial[
"books"
] = self.instance.book_set.values_list("pk", flat=True)
def _save_m2m(self):
super()._save_m2m()
self.instance.book_set.clear()
self.instance.book_set.add(*self.cleaned_data["books"])
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
form = AuthorForm
fields = ("name", "books")
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django App for You
Django GDPR Cookie Consent app
For Django websites that use cookies.
Django App for You