I have a simple Django model resembling:
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.
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:
cl开发者_Python百科ass 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?
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) ForeignKey
s. Something like:
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']
I'm using 1.5 and list_filter = ['memberdata__user']
seems like it would work.
精彩评论