I'm getting closer!  

First I found this note in the Content Types docs that explains why what I 
was doing does NOT work:
https://docs.djangoproject.com/en/1.4/ref/contrib/contenttypes/#django.contrib.contenttypes.generic.GenericForeignKey

*Due to the way 
GenericForeignKey<https://docs.djangoproject.com/en/1.4/ref/contrib/contenttypes/#django.contrib.contenttypes.generic.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:
https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey


That I adapted to this for my admin form:
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "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 django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to