@@ -89,20 +89,6 @@ def inject_rename_contenttypes_operations(
8989 migration .operations .insert (inserted + index , operation )
9090
9191
92- def get_contenttypes_and_models (app_config , using , ContentType ):
93- if not router .allow_migrate_model (using , ContentType ):
94- return None , None
95-
96- ContentType .objects .clear_cache ()
97-
98- content_types = {
99- ct .model : ct
100- for ct in ContentType .objects .using (using ).filter (app_label = app_config .label )
101- }
102- app_models = {model ._meta .model_name : model for model in app_config .get_models ()}
103- return content_types , app_models
104-
105-
10692def create_contenttypes (
10793 app_config ,
10894 verbosity = 2 ,
@@ -117,29 +103,33 @@ def create_contenttypes(
117103 if not app_config .models_module :
118104 return
119105
120- app_label = app_config .label
121106 try :
122- app_config = apps .get_app_config (app_label )
107+ app_config = apps .get_app_config (app_config . label )
123108 ContentType = apps .get_model ("contenttypes" , "ContentType" )
124109 except LookupError :
125110 return
126111
127- content_types , app_models = get_contenttypes_and_models (
128- app_config , using , ContentType
129- )
112+ if not router .allow_migrate_model (using , ContentType ):
113+ return
130114
131- if not app_models :
115+ all_model_names = {model ._meta .model_name for model in app_config .get_models ()}
116+
117+ if not all_model_names :
132118 return
133119
120+ ContentType .objects .clear_cache ()
121+
122+ existing_model_names = set (
123+ ContentType .objects .using (using )
124+ .filter (app_label = app_config .label )
125+ .values_list ("model" , flat = True )
126+ )
127+
134128 cts = [
135- ContentType (
136- app_label = app_label ,
137- model = model_name ,
138- )
139- for (model_name , model ) in app_models .items ()
140- if model_name not in content_types
129+ ContentType (app_label = app_config .label , model = model_name )
130+ for model_name in sorted (all_model_names - existing_model_names )
141131 ]
142132 ContentType .objects .using (using ).bulk_create (cts )
143133 if verbosity >= 2 :
144134 for ct in cts :
145- print ("Adding content type '%s | %s'" % ( ct .app_label , ct .model ) )
135+ print (f "Adding content type '{ ct .app_label } | { ct .model } '" )
0 commit comments