Tuesday, November 19, 2013

Re: Filter ForeignKey values in model's admin view

On 19/11/13 17:10, Michal Ludvig wrote:

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?


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






0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate