Django Admin filter on Foreign Key property

admin, django, filter, python

Solution

See https://code.djangoproject.com/ticket/3400 . It works ok in django 1.3 :)

class Room(models.Model):
    house = models.ForeignKey(House)

    def __unicode__(self):
        return self.house.town.name

class Booking(models.Model):
    room = models.ForeignKey(Room)

    def __unicode__(self):
        return self.room.house.town.name

class BookingOpts(admin.ModelAdmin):
    list_filter = ('room__house__town',)
    raw_id_admin = ('room', )

admin.site.register(Town)
admin.site.register(House)
admin.site.register(Room)
admin.site.register(Booking, BookingOpts)

Problem

I want to add a filter in an admin changelist by a property of a foreign key, e.g. ``` class Address(model.Models): street = models.CharField(max_length=25) city = models.CharField(max_length=25) country = models.CharField(max_length=25) class Customer(models.Model): name = models.CharField(max_length=25) address = models.ForeignKey(Address) ``` Let's say in the Customer admin changelist I want to show a filter by city and country (so show me all customers in a particular country or city). But the standard list_filter() functionality seems to only allow filtering by fields directly on the model and not on any of its foreign key. I've tried: ``` list_filter = ("address__country",) ``` or ``` list_filter = ("address.country",) ``` but I always get the same type of error: ``` 'address__country' is not a callable or an attribute ``` Any suggestions would be welcome. Is there some special naming convention/syntax to allow filtering on FK properties?

Original source

Related problems