from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
class Reader(models.Model):
name = models.CharField(max_length=100)
books = models.ManyToManyField(Book)
from django.contrib import admin
from .models import Book, Reader
class ReaderAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super().get_queryset(request)
# 可以过滤掉没有书籍的读者
return qs.filter(books__isnull=False)
# 修改formfield_for_manytomany方法,只显示有书籍的读者
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == 'books':
kwargs['queryset'] = Book.objects.filter(reader__isnull=False)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Book)
admin.site.register(Reader, ReaderAdmin)
现在,在阅读器的Admin页面中,您将只能看到分配了书籍的读者,并且您将只能为那些读者选择存在的书籍。