views:

530

answers:

2

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.

A: 

You can write your own manager to you model (special for formset) and use it.

http://docs.djangoproject.com/en/dev/topics/db/managers/

bluszcz
Thanks a lot. That looks like a nice solution, although I will have to use some another (non default) manager in all other places cause I need those filtered-out objects everywhere just not in the admin page. I'ts a pity that there is no admin option to provide custom, not default manager for inlines.
Łukasz Korzybski
Well I found that I one can provide non default queryset/manager for inlines by subclassing BaseInlineFormSet (http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#model-formsets) and then provide this formset to InlineModelAdmin by 'formset' property. Nice!
Łukasz Korzybski
+2  A: 

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
    ...
Łukasz Korzybski
Excellent - this is just what I was looking for. Using the private property '_queryset' stops the the SQL query from firing dozens of times per page. Very nice.
richbs