Django admin, filter objects for inline formset

前端 未结 3 943
忘掉有多难
忘掉有多难 2020-12-14 04:14

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 mo

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 05:12

    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.

提交回复
热议问题