Django管理员,用于内联表单集过滤对象 [英] Django admin, filter objects for inline formset

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

问题描述

我有一个内联表单集,我想排除一些模型对象不被显示在表单集中。



有一个模型B有外键模型A,所以它是1:n(一个对象有很多B对象)的关系。现在在一个管理员编辑页面上,我有一个B的内联。我想知道是否可能以某种方式过滤在内联表单集之前的B对象的列表,所以不是所有的B对象相关的A进入表单集。 p>

解决方案

回答自己的问题似乎有点奇怪,但我发现另一个解决方案;)



有一个问题,提供一个formset的自定义查询集,在这种情况下没有钩子的内联表单。所以我将BaseInlineFormSet子类化并覆盖了get_queryset方法。然后我只是在InlineModelAdmin中提供这个表单,并完成了。



示例:

  class MyFormSet(BaseInlineFormSet):
def get_queryset(self):
如果不是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
...


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

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 ;)

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.

Example:

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

and admin class:

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

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

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