<s> from __future__ import unicode_literals <EOL> from functools import partial <EOL> from tastypie import fields <EOL> from tastypie . resources import Resource <EOL> from tastypie . exceptions import ApiFieldError <EOL> from django . db import models <EOL> from django . core . exceptions import ObjectDoesNotExist <EOL> from . resources import GenericResource <EOL> class GenericForeignKeyField ( fields . ToOneField ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , to , attribute , ** kwargs ) : <EOL> if not isinstance ( to , dict ) : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> if len ( to ) <= <NUM_LIT:0> : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> for k , v in to . items ( ) : <EOL> if not issubclass ( k , models . Model ) or not issubclass ( v , Resource ) : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> super ( GenericForeignKeyField , self ) . __init__ ( to , attribute , ** kwargs ) <EOL> def get_related_resource ( self , related_instance ) : <EOL> self . _to_class = self . to . get ( type ( related_instance ) , None ) <EOL> if self . _to_class is None : <EOL> raise TypeError ( '<STR_LIT>' % type ( related_instance ) ) <EOL> return super ( GenericForeignKeyField , self ) . get_related_resource ( related_instance ) <EOL> @ property <EOL> def to_class ( self ) : <EOL> if self . _to_class and not issubclass ( GenericResource , self . _to_class ) : <EOL> return self . _to_class <EOL> return partial ( GenericResource , resources = self . to . values ( ) ) <EOL> def resource_from_uri ( self , fk_resource , uri , request = None , related_obj = None , related_name = None ) : <EOL> try : <EOL> obj = fk_resource . get_via_uri ( uri , request = request ) <EOL> fk_resource = self . get_related_resource ( obj ) <EOL> return super ( GenericForeignKeyField , self ) . resource_from_uri ( fk_resource , uri , request , related_obj , related_name ) <EOL> except ObjectDoesNotExist : <EOL> raise ApiFieldError ( "<STR_LIT>" % uri ) <EOL> def build_related_resource ( self , * args , ** kwargs ) : <EOL> self . _to_class = None <EOL> return super ( GenericForeignKeyField , self ) . build_related_resource ( * args , ** kwargs ) </s>
