<s> import itertools <EOL> from django . apps import AppConfig , apps <EOL> from django . db . models import DateField , DateTimeField <EOL> from django . db . models . fields . related import RelatedField , ReverseSingleRelatedObjectDescriptor <EOL> from natural_query . fields import NaturalQueryField <EOL> from natural_query . query import NaturalQueryDescriptor , DateNaturalQueryDescriptor , DateTimeNaturalQueryDescriptor , PrimaryKeyNaturalQueryDescriptor , ReverseSingleRelatedObjectNaturalQueryDescriptor <EOL> class NaturalQueryConfig ( AppConfig ) : <EOL> name = '<STR_LIT>' <EOL> def naturalize_model ( self , model ) : <EOL> if not isinstance ( model . pk , PrimaryKeyNaturalQueryDescriptor ) : <EOL> model . pk = PrimaryKeyNaturalQueryDescriptor ( ) <EOL> non_natural_fields = [ field for field in model . _meta . fields if <EOL> not isinstance ( field , NaturalQueryField ) ] <EOL> for field in non_natural_fields : <EOL> if not hasattr ( model , field . name ) : <EOL> if isinstance ( field , DateTimeField ) : <EOL> setattr ( model , field . name , DateTimeNaturalQueryDescriptor ( field . name ) ) <EOL> elif isinstance ( field , DateField ) : <EOL> setattr ( model , field . name , DateNaturalQueryDescriptor ( field . name ) ) <EOL> else : <EOL> setattr ( model , field . name , NaturalQueryDescriptor ( field . name ) ) <EOL> non_natural_foreign_key_fields = [ field for field in model . _meta . fields if <EOL> isinstance ( field , RelatedField ) ] <EOL> for field in non_natural_foreign_key_fields : <EOL> relation_id_attribute_name = '<STR_LIT>' % field . name <EOL> if not hasattr ( model , relation_id_attribute_name ) : <EOL> setattr ( model , relation_id_attribute_name , NaturalQueryDescriptor ( relation_id_attribute_name ) ) <EOL> def naturalize_model_relationships ( self , model ) : <EOL> non_natural_foreign_key_fields = [ field for field in model . _meta . fields if <EOL> isinstance ( field , RelatedField ) ] <EOL> for field in non_natural_foreign_key_fields : <EOL> if isinstance ( getattr ( model , field . name ) , ReverseSingleRelatedObjectDescriptor ) : <EOL> descriptor = ReverseSingleRelatedObjectNaturalQueryDescriptor ( field ) <EOL> setattr ( model , field . name , descriptor ) <EOL> def ready ( self ) : <EOL> """<STR_LIT>""" <EOL> app_configs = apps . get_app_configs ( ) <EOL> models = tuple ( itertools . chain . from_iterable ( app_config . get_models ( ) for app_config in app_configs ) ) <EOL> for model in models : <EOL> self . naturalize_model ( model ) <EOL> for model in models : <EOL> self . naturalize_model_relationships ( model ) </s>
