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

前端 未结 7 1675
灰色年华
灰色年华 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:46

    A generalized reusable version of the great @darklow's answer:

    def make_RelatedOnlyFieldListFilter(attr_name, filter_title):
    
        class RelatedOnlyFieldListFilter(admin.SimpleListFilter):
            """Filter that shows only referenced options, i.e. options having at least a single object."""
            title = filter_title
            parameter_name = attr_name
    
            def lookups(self, request, model_admin):
                related_objects = set([getattr(obj, attr_name) for obj in model_admin.model.objects.all()])
                return [(related_obj.id, unicode(related_obj)) for related_obj in related_objects]
    
            def queryset(self, request, queryset):
                if self.value():
                    return queryset.filter(**{'%s__id__exact' % attr_name: self.value()})
                else:
                    return queryset
    
        return RelatedOnlyFieldListFilter
    

    Usage:

    class CityAdmin(ModelAdmin):
        list_filter = (
            make_RelatedOnlyFieldListFilter("country", "Country with cities"),
        )
    
    0 讨论(0)
提交回复
热议问题