示例模型:
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 as TabularInline,但只显示Connect 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列表中可见。
仅适用于保存Connect(仅保存与book1__book_type = 0的连接)。
答案 0 :(得分:2)
formfield_for_foreignkey
应该做你想做的事:
class InlineConnectn(admin.TabularInline):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "book1":
kwargs["queryset"] = Foo.objects.filter(book1__book_type=1)
return super(InlineConnectn, self).formfield_for_foreignkey(db_field, request, **kwargs)