Opened 18 months ago

Closed 17 months ago

Last modified 17 months ago

#21702 closed Cleanup/optimization (fixed)

Consider providing apps.get_model("app_label.ModelName")

Reported by: aaugustin Owned by: nobody
Component: Core (Other) Version: master
Severity: Normal Keywords: app-loading
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Basically:

--- a/django/apps/registry.py
+++ b/django/apps/registry.py
@@ -224,16 +224,21 @@ class Apps(object):
             )
         return model_list
 
-    def get_model(self, app_label, model_name):
+    def get_model(self, app_label, model_name=None):
         """
         Returns the model matching the given app_label and model_name.
 
+        As a shortcut, this function also accepts a single argument
+        <app_label>.<model_name>.
+
         model_name is case-insensitive.
 
         Raises LookupError if no application exists with this label, or no
         model exists with this name in the application.
         """
         self.populate_models()
+        if model_name is None:
+            app_label, _, model_name = app_label.partition('.')
         return self.get_app_config(app_label).get_model(model_name.lower())
 
     def register_model(self, app_label, model):

This would avoid repeating the splitting logic in many call sites.

Same question for get_registered_model.

Change History (5)

comment:1 Changed 18 months ago by mjtamlyn

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

And also avoids repeating the logic in multiple external applications.

comment:2 Changed 17 months ago by aaugustin

  • Has patch set
  • Triage Stage changed from Accepted to Ready for checkin

PR: https://github.com/django/django/pull/2215

Anyone interested in reviewing it?

comment:3 Changed 17 months ago by Aymeric Augustin <aymeric.augustin@…>

  • Resolution set to fixed
  • Status changed from new to closed

In 3c47786cb91617b3757e57b6bfeda06ef14e561a:

Fixed #21702 -- get_model('app_label.ModelName').

Also added tests for get_model.

comment:4 Changed 17 months ago by Aymeric Augustin <aymeric.augustin@…>

In f901b4d6c869f4cfb4fc28a861c481f28e46bb3f:

Took advantage of the new get_model API. Refs #21702.

comment:5 Changed 17 months ago by aaugustin

get_registered_model doesn't need the same treatment because it's used in only two places, it's a private API and I'd like to remove it eventually.

Note: See TracTickets for help on using tickets.
Back to Top