filter foreignkey field in django admin

后端 未结 7 1296
感情败类
感情败类 2020-12-02 20:42

I have these models:

class Entity(models.Model):
       name=models.CharField(max_length=100)
      
class Theme(models.Model):
   name=models.CharField(max_l         


        
相关标签:
7条回答
  • 2020-12-02 20:51

    look here http://books.agiliq.com/projects/django-admin-cookbook/en/latest/filter_fk_dropdown.html

    @admin.register(Hero)
    class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
        ...
        def formfield_for_foreignkey(self, db_field, request, **kwargs):
            if db_field.name == "category":
                kwargs["queryset"] = Category.objects.filter(name__in=['God', 'Demi God'])
            return super().formfield_for_foreignkey(db_field, request, **kwargs)
    
    0 讨论(0)
  • 2020-12-02 20:52

    I faced with the need to add filter to the foreignKey queryset of the parent ModelAdmin class (which all other ModelAdmins inherit from), that is, I can’t know exactly which model I need, this is my solution: db_field.related_model.objects.filter()

    class TSModelAdmin(admin.ModelAdmin):
       exclude = ('site',)
        ...
    
          def formfield_for_foreignkey(self, db_field, request, **kwargs):
            if db_field.related_model:
                kwargs["queryset"] = 
                db_field.related_model.objects.filter(site=request.user.user_profile.site)
            return super().formfield_for_foreignkey(db_field, request, **kwargs)
    

    used django version 2.2.10

    0 讨论(0)
  • 2020-12-02 20:55

    Use the render_change_form method:

    class CompanyAdmin(admin.ModelAdmin):
        def render_change_form(self, request, context, *args, **kwargs):
             context['adminform'].form.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
             return super(CompanyAdmin, self).render_change_form(request, context, *args, **kwargs)
    
    0 讨论(0)
  • 2020-12-02 21:03

    Another option is to create a custom model form where the queryset attribute of the theme field will be fine tuned to meet your needs.

    class CompanyForm(ModelForm):
        class Meta:
            model = CompanyForm
            fields = __all__ # or a tuple of fields
    
        def __init__(self, *args, **kwargs):
            super(CompanyForm, self).__init__(*args, **kwargs)
            if self.instance: # Editing and existing instance
                self.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
    

    This model form can be also reused outside of the django admin area.

    0 讨论(0)
  • 2020-12-02 21:05

    In Django 3 it is easy :

    class CompanyAdmin(admin.ModelAdmin):
        list_display = ('name','theme')
        list_filter = ('theme__name',)
    
    admin.site.register(Company,CompanyAdmin)
    

    This will show you a filter on the right of your screen with the list of your theme's name.

    0 讨论(0)
  • 2020-12-02 21:07

    A bit unrelated, but similar to this so I'll post this here.

    I was looking for a way to remove the NULL choice selection on a ModelForm foreignkey field. I first thought I could filter the queryset as is done in other answers here, but that didn't work.

    I found that I can filter the entry where the pk value is NULL like this in the get_form method:

    
    class CompanyAdmin(admin.ModelAdmin):
        def get_form(self, request, obj=None, **kwargs):
            form = super().get_form(request, obj, **kwargs)
            # remove null choice
            form.base_fields["theme"].choices = ((pk, display) for pk, display in form.base_fields["theme"].choices if pk)
            return form
    
    0 讨论(0)
提交回复
热议问题