示例模型:
class Book(models.Model):
TYPES = (
(0, 'Sci-fi')
(1, 'Biography')
)
title = models.CharField(...)
book_type = models.CharField(max_length=1, choices=TYPES)
class Connect(models.Model):
book1 = models.ForeignKey(Book, related_name='book_1')
book2 = models.ForeignKey(Book, related_name='book_2')
我想做一个想法,在 Book 中将 Connect 显示为 TabularInline,但只显示 Connect where book1__book_type = 0
我试着这样做:
class ConnectFormSet(BaseInlineFormSet):
def get_queryset(self):
if not hasattr(self, '_queryset'):
qs = super(ConnectionFormSet, self).get_queryset().filter('book1__book_type':0)
self._queryset = qs
return self._queryset
class InlineConnectn(admin.TabularInline):
fk_name = 'book1'
model = Connect
extra = 0
formset = ConnectFormSet
但它不像我想要的那样工作。在 TabularInline 中的 Connect 列表中仍然可以看到所有连接。
作品仅保存连接(仅保存带有 book1__book_type = 0 的连接)。