Code

Opened 2 years ago

Closed 2 years ago

#17765 closed Bug (worksforme)

Better model 'app_label' introspection using 'INSTALLED_APPS'

Reported by: fengb Owned by: nobody
Component: Database layer (models, ORM) Version: 1.3
Severity: Normal Keywords: app_label
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: yes Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Currently, the model generates "app_label" by taking the second to last module:

django.contrib.auth.models.User -> auth
newproj.newapp.models.Newmodel -> newapp
newproj.newapp.models.db.Newmodel -> models

The last example doesn't make any sense. I propose that we match the module chain against 'INSTALLED_APPS' to find the correct app.

Attachments (0)

Change History (4)

comment:1 Changed 2 years ago by anonymous

  • Needs documentation unset
  • Needs tests set
  • Patch needs improvement unset

I have an implementation available on Github:

https://github.com/fengb/django/tree/app-label-introspect

Tests are failing but they look somewhat unrelated. I do not have enough context to fix them.

comment:2 Changed 2 years ago by fengb

Crap, I didn't notice that my description formatting gotten eaten...

Middle "paragraph" should be:

  • django.contrib.auth.models.User -> auth
  • newproj.newapp.models.Newmodel -> newapp
  • newproj.newapp.models.db.Newmodel -> models

comment:3 Changed 2 years ago by aaugustin

  • Has patch set
  • Triage Stage changed from Unreviewed to Accepted
  • Type changed from New feature to Bug

Your proposal looks correct. But maybe Django should just forbid to define modules outside of <app_label>.models — this deserves a bit more investigation.

Maybe we should raise an error when app_label isn't in INSTALLED_APPS. Currently it's possible to import models from an app that isn't in INSTALLED_APPS, and it can lead to hard-to-debug errors. This is related to the app-refactor project — see #3591.

Last edited 2 years ago by aaugustin (previous) (diff)

comment:4 Changed 2 years ago by aaugustin

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

I just remembered that Django provide an option exactly for this:

https://docs.djangoproject.com/en/dev/ref/models/options/#app-label

Last edited 2 years ago by aaugustin (previous) (diff)

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.