Django admin,过滤内联表单集的对象 [英] Django admin, filter objects for inline formset

查看:38
本文介绍了Django admin,过滤内联表单集的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内联表单集,我想从表单集中显示的某些模型对象中排除.

I've got an inline formset and I would like to exclude some model objects from being displayed in the formset.

例如.模型 B 具有模型 A 的外键,因此它是 1:n(A 对象有多个 B 对象)关系.现在在 A 管理编辑页面上,我有 B 的内联.我想知道是否有可能在内联表单集呈现之前以某种方式过滤 B 对象的列表,因此并非所有与 A 相关的 B 对象都会进入表单集.

For eg. there is model B which has foreign key to model A, so it is a 1:n (A object has many B objects) relationship. Now on A admin edit page I've got inlines of B. I wonder if it is possible somehow to filter the list of B objects before the inline formset is rendered, so not all B objects related do A gets into the formset.

推荐答案

回复自己的问题似乎有点奇怪,但我找到了另一个解决方案 ;)

Replying to own question may seem a bit odd but I found another solution ;)

向表单集提供自定义查询集时出现问题,对于内联表单集没有钩子.所以我继承了 BaseInlineFormSet 并覆盖了 get_queryset 方法.然后我只需在 InlineModelAdmin 中提供这个表单集就完成了.

There was a problem to provide custom queryset to a formset, there is no hook in case of inline formsets for this. So I subclassed BaseInlineFormSet and overridden the get_queryset method. Then I just provide this formset in InlineModelAdmin and it's done.

示例:

class MyFormSet(BaseInlineFormSet):
    def get_queryset(self):
        if not hasattr(self, '_queryset'):
            qs = super(MyFormSet, self).get_queryset().filter(main=False)
            self._queryset = qs
        return self._queryset

和管理类:

class MyInline(admin.TabularInline):
    model = m.MyModel
    formset =  MyFormSet
    ...

这篇关于Django admin,过滤内联表单集的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆