class Author(models.Model): name = models.CharField(max_length=50) desc = models.CharField(max_length=50) class Book(models.Model): author = models.ForeignKey(Author) title= models.CharField(max_length=50) class BookPrio:: author = models.ForeignKey(Author) book = models.ForeignKey(Book) prio = models.IntegerField()
我没有看到任何简单的方法来访问已编辑的对象,因此我将formfield_for_foreignkey定义放在change_view中,并在view函数中分配了内联.
class BookPrioInline(admin.TabularInline): model = BookPrio class AuthorAdmin(admin.ModelAdmin): inlines = (BookPrioInline,) def change_view(self, request, object_id, extra_context=None): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'book': kwargs['queryset'] = Book.objects.filter(author__id=object_id) return super(ItemInline, self).formfield_for_foreignkey(db_field, request, **kwargs) ItemInline.formfield_for_foreignkey = formfield_for_foreignkey self.inline_instances = [ItemInline(self.model, self.admin_site)] return super(AuthorAdmin, self).change_view(request, object_id, extra_context=extra_context) admin.site.register(Author, AuthorAdmin)