Filter ForeignKey values in model's admin view

43 views
Skip to first unread message

Michal Ludvig

unread,
Nov 18, 2013, 11:10:10 PM11/18/13
to django...@googlegroups.com

Hi

I've got two Django models: Contact and Group, where Group has two fields: contact and contact_primary linked to Contact. Like this:

class Group(models.Model):
    name = models.CharField(max_length=200)
    contacts = models.ManyToManyField(Contact)
    contact_primary = models.ForeignKey(Contact)

In the admin interface I can select a number of Contacts for the contacts field and then I want to see only these selected contacts in the contact_primary dropdown. Not necessarily immediately but definitely on subsequent admin view reloads. As it is now I can see all my Contacts, whether they're selected in the ManyToMany field or not.

How can I restrict the Contacts displayed for contact_primary only to those selected in contacts?

Thanks!

Michal

Michal Ludvig

unread,
Nov 19, 2013, 4:27:41 PM11/19/13
to django...@googlegroups.com
Anyone? I don't think it should be too difficult but can't put all the pieces together.

In other words what I need is - in the Admin interface there's a drop-down list for "contact_primary" and a multi-select for "contacts".

The "contacts" displays Contact.objects.all() - that's good, but so does "contact_primary" and that's not good. What I only want to display there is the particular group's group.contacts.all() - i.e. only those Contacts selected in the multi-select field. I'm sure it must be doable but I don't know how.

Do I need a GroupAdmin(admins.ModelAdmin) class and somehow filter it in there? BTW I don't mind that upon creating a new Group the drop-down for contact_primary will be empty, I can live with that.

Any ideas?

Thanks!

Michal






tim

unread,
Nov 19, 2013, 7:50:25 PM11/19/13
to django...@googlegroups.com
I don't see an easy way to do this offhand. Filtering the ForeignKey queryset using ModelAdmin.formfield_for_foreignkey [1] seems close, but I don't think there's any way to incorporate the values from the M2M field in your filtering. Have you considered writing some JavaScript to do the filtering on the client-side?

Reply all
Reply to author
Forward
0 new messages