django filter in admin on reverse related field

Question:

I have the models:

class Supplier(models.Model):
    unique_id = models.IntegerField(unique=True)
    name = models.CharField(max_length=255, unique=True)
    address = models.CharField(max_length=255, blank=True, null=True)
    email = models.EmailField(blank=True, null=True)
    telephone = models.CharField(max_length=15, blank=True, null=True)

class PaymentMethod(models.Model):
    unique_id = models.CharField(max_length=3)
    supplier = models.ForeignKey(Supplier, null=True)
    last_updated = models.DateTimeField(auto_now=True)

For which I trying to add a filter to suppliers for payment method:

@admin.register(Supplier)
class SupplierAdmin(admin.ModelAdmin):
    list_display = ('unique_id', 'name', 'last_updated')
    ordering = ('unique_id',)
    list_filter = ('payment_method__unique_id')
    inlines = [PaymentMethodInline, ]

However I seem to have the list_filter incorrectly specified as I get the below error:

<class 'etariff.admin.SupplierAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'payment_method__unique_id', which does not refer to a Field.
Asked By: Yunti

||

Answers:

To use the related payment methods, you can do

list_filter = ('paymentmethod',)

Note there is no underscore, and remember the trailing comma to make it a tuple.

If you want to display the unique ids of related payment methods, then I think you’ll have to write your own ListFilter class. See the docs for an example.

Answered By: Alasdair
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.