外键属性上的Django Admin过滤器 [英] Django Admin filter on Foreign Key property

查看:28
本文介绍了外键属性上的Django Admin过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过外键的属性在管理更改列表中添加过滤器,例如

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).

但是标准的 list_filter() 功能似乎只允许直接在模型上按字段进行过滤,而不能按其任何外键进行过滤.我试过了:

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",)

list_filter = ("address.country",)

但我总是遇到相同类型的错误:

but I always get the same type of error:

 'address__country' is not a callable or an attribute 

欢迎提出任何建议.是否有一些特殊的命名约定/语法来允许过滤 FK 属性?

Any suggestions would be welcome. Is there some special naming convention/syntax to allow filtering on FK properties?

推荐答案

参见 https://code.djangoproject.com/ticket/3400 .它在 django 1.3 中工作正常 :)

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)

这篇关于外键属性上的Django Admin过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆