Monday, April 29, 2013

Re: I need help doing a linked lookup in admin

I'm getting closer! 

First I found this note in the Content Types docs that explains why what I was doing does NOT work:

Due to the way GenericForeignKey is implemented, you cannot use such fields directly with filters (filter() and exclude(), for example) via the database API.

Then I found this sample code in the admin docs:

That I adapted to this for my admin form:
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if == "ship_to":
            kwargs["queryset"] = StreetAddress.objects.filter(po__supplier__street_address__location="shipto")
        return super(POAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

Note that while this is my "PO" data model, I used the model belonging to the address data "StreetAddress".  This is because which model does the object.filter() is the one whose __unicode__ function is called to get a representation of each record found for the list selection dialogue.  Which means, for my PO database, it describes each address by its PO number (which are the same number) making it hard to tell the addresses apart!  By using the StreetAddress model, it uses its __unicode__ instead, which makes a mini-summary of each address.  Much clearer.

This is not a perfect solution though because when I try to SAVE an edited PO record I get an error:

MultipleObjectsReturned: get() returned more than one StreetAddress -- it returned 2! Lookup parameters were {'id': u'2'}

I'm going to go back to letting it list all "ship to" addresses for all companies until I figure out what this error even means!

Another problem is its listing both address choices with the same description.  Another mystery to ponder.

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To post to this group, send email to
Visit this group at
For more options, visit

No comments:

Post a Comment