开发者

Django admin, filter objects for inline formset

开发者 https://www.devze.com 2022-12-16 20:05 出处:网络
I\'ve got an inline formset and I would like to exclude some model objects from being displayed in the formset.

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
    ...


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

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


In Django 3, you should use formfield_for_foreignkey.

here is a working example :

class CaracteristiqueInline(admin.TabularInline):
  model = Caracteristique
  formset = FiltreCaracteristiqueInline

  def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "id_Champ": # The FK in my table Caracteristique
        kwargs["queryset"] = Champ.objects.filter(est_DC_Champ=False)
        # Champ is the parent table of Caracteristique
        # est_DC_Champ is a field of the table Champ
    return super().formfield_for_foreignkey(db_field, request, **kwargs)
  extra = 0

With this, in your Tabular View, the choices in the dropdown of your FK Field will be filtered.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号