Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list filter by custom list display field in django admin

I have following model admin. I'm displaying custom field in list view.

class CustomerAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'email', 'state')
    search_fields = ('first_name', 'last_name', 'email')
    list_filter = ('state',)
    def state(self, obj):
        address = Address.objects.filter(owner=obj.id)
        if address:
            return address.state
    return None

I tried above but it gives an error "list_filter[0]' refers to 'state' which does not refer to a Field." So I want filter records by state. So how I can do this in django 1.5?

like image 495
Vijay Avatar asked Dec 05 '25 04:12

Vijay


1 Answers

list_filter works on related models.

If model looks like that:

class Address(models.Model):
    owner = models.OneToOneField(Customer, models.CASCADE,
                             related_name='address')
    state = models.CharField(max_length=20)

You can use address__state in ModelAdmin. For example:

@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'email', 'state')
    search_fields = ('first_name', 'last_name', 'email')
    list_filter = ('address__state', )

Note that list_display doesn't work this way!

like image 184
returnsnull.dev Avatar answered Dec 07 '25 18:12

returnsnull.dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!