在多对多字段上启用Django Admin过滤器

时间:2022-09-02 20:13:06

I have a simple Django model resembling:

我有一个简单的Django模型,类似于:

class Address(models.Model):
    blah

class MemberData(models.Model):
    user = models.ForeignKey(User)
    addresses = models.ManyToManyField(Address)

I want to expose the Address model in admin to allow a user to filter Address records by their associated user. e.g.

我想在admin中公开Address模型,以允许用户通过其关联用户过滤地址记录。例如

class AddressAdmin(admin.ModelAdmin):
    model = Address
    list_filter = [???]

The ModelAdmin.list_filter property allows this, but I'm not sure what field name to use to support my many-to-many relationship. If the Address model has a direct reference to the MemberData model, I could do something like:

ModelAdmin.list_filter属性允许这样做,但我不确定使用哪个字段名来支持我的多对多关系。如果Address模型直接引用MemberData模型,我可以执行以下操作:

class AddressAdmin(admin.ModelAdmin):
    model = Address
    list_filter = ['memberdata__user']

Is there any equivalent syntax for an indirect many-to-many relationship? If not, is there any workaround to accomplish the same end?

是否存在间接多对多关系的等效语法?如果没有,是否有任何解决方法来完成同样的目的?

2 个解决方案

#1


7  

I believe in a case like this, you could make a trivial through model for your M2M relation, and then use the normal syntax to follow the (now explicit) ForeignKeys. Something like:

我相信这样的情况,你可以为你的M2M关系制作一个简单的模型,然后使用正常的语法来跟随(现在显式的)ForeignKeys。就像是:

class Address(models.Model):
    blah

class MemberData(models.Model):
    user = models.ForeignKey(User)
    addresses = models.ManyToManyField(Address,through='MemberAddress')

class MemberAddress(models.Model):
    member = models.ForeignKey(MemberData)
    address = models.ForeignKey(Address)

and in the admin:

并在管理员:

class AddressAdmin(admin.ModelAdmin):
    model = Address
    list_filter = ['memberaddress_set__member__user']

#2


2  

I'm using 1.5 and list_filter = ['memberdata__user'] seems like it would work.

我正在使用1.5和list_filter = ['memberdata__user']似乎它会起作用。

#1


7  

I believe in a case like this, you could make a trivial through model for your M2M relation, and then use the normal syntax to follow the (now explicit) ForeignKeys. Something like:

我相信这样的情况,你可以为你的M2M关系制作一个简单的模型,然后使用正常的语法来跟随(现在显式的)ForeignKeys。就像是:

class Address(models.Model):
    blah

class MemberData(models.Model):
    user = models.ForeignKey(User)
    addresses = models.ManyToManyField(Address,through='MemberAddress')

class MemberAddress(models.Model):
    member = models.ForeignKey(MemberData)
    address = models.ForeignKey(Address)

and in the admin:

并在管理员:

class AddressAdmin(admin.ModelAdmin):
    model = Address
    list_filter = ['memberaddress_set__member__user']

#2


2  

I'm using 1.5 and list_filter = ['memberdata__user'] seems like it would work.

我正在使用1.5和list_filter = ['memberdata__user']似乎它会起作用。