1

示例模型:

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 的连接)。

4

1 回答 1

3

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)
于 2013-08-12T22:37:09.383 回答