Can I make list_filter in django admin to only show referenced ForeignKeys?

前端 未结 7 1721
灰色年华
灰色年华 2020-12-02 07:02

I have a django application which has two models like this:

class MyModel(models.Model):
    name = models.CharField()
    country = models.ForeignKey(\'Coun         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 07:25

    As of Django 1.8, there is a built in RelatedOnlyFieldListFilter, which you can use to show related countries.

    class MyModelAdmin(admin.ModelAdmin):
        list_display = ('name', 'country',)
        list_filter = (
            ('country', admin.RelatedOnlyFieldListFilter),
        )
    

    For Django 1.4-1.7, list_filter allows you to use a subclass of SimpleListFilter. It should be possible to create a simple list filter that lists the values you want.

    If you can't upgrade from Django 1.3, you'd need to use the internal, and undocumented, FilterSpec api. The Stack Overflow question Custom Filter in Django Admin should point you in the right direction.

提交回复
热议问题