The GenericForeignKey class is perfect for recovering the object it references but leaves no way to recover itself and the field names it stores.
Its get function only returns the object it references or an error.
DoesNotExist when it isn't set on an instance.
AttributeError when accessed from the model class.
This one line patch and doc test changes the behavior of get to return the GenericForeignKey instance when accessed from the model class thereby allowing access to the content type and primary key field names.
generic.diff​ (1.2 KB) - added by kgoudeaux <kgoudeaux@…> 11 years ago.
You need to go through Model._meta.fields to get at this info.
The information for each field is in Meta, of course, but there is no way to determine which fields correspond with what for a generic foreign key.
You can guess 'content_type' and 'object_id' but this won't always be the case.
It seems reasonable that GenericForeignKey would allow some way to programmatically determine which fields in Meta that it references when interacting with the Class, as opposed to an instance.
I just tried this to make auditTrail (as described in the wiki) also provide the genericforeign key on the original item. Works perfectly.
It seems this was fixed in r9562.