Ebolasudan
Ebolasudan

Reputation: 121

valueerror invalid model reference, how can i reference correctly

I had to change a number of my ManyToMany relations to reference a string instead of importing the model into the file so to avoid a number of circular importing errors.

but when trying to run, now I am getting this error.

ValueError: Invalid model reference 'dsi.administration.libraries.Library'. String model references must be of the form 'app_label.ModelName'.

I don't know what would be the best way to reference this and I'd love to get anyone's input on this.

the reference in question

    models.ManyToManyField("dsi.administration.libraries.Library", verbose_name='library choices')

settings.py installed modules

SHARED_APPS = (
    "storages",
    "django_tenants",  # mandatory
    'dsi.events.event',
    'dsi.administration.libraries',
    'dsi.account'
)

the app folder structure

├── dsi
│   ├── account
│   │   ├──__init__.py
│   │   ├── models.py
│   ├── events
│   │   ├── event
|   │   │   ├── __init__.py
|   │   │   ├── models.py
│   │   ├──__init__.py
│   ├── administration
│   │   ├── libraries
|   │   │   ├── __init__.py
|   │   │   ├── models.py
│   │   ├── general
|   │   │   ├── __init__.py
|   │   │   ├── models.py
│   │   ├── __init__.py
│   ├── __init__.py
│   ├── urls.py
│   └── settings.py
├── manage.py

Upvotes: 1

Views: 499

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

As stated in the documentation:

To refer to models defined in another application, you can explicitly specify a model with the full application label.

The app label (unless specified in the app config) is by default the last part of the full python path (the app name) to the app, so libraries, not dsi.administration.libraries.Library. If you have an AppConfig, then the AppConfig will specify the name of the app, such AppConfig can look like:

# dsi/administration/libraries/apps.py

from django.apps import AppConfig

class AppNameConfig(AppConfig):
    name = 'dsi.administration.libraries'

Therefore here the label would be libraries. If you thus found the label of the app, you should specify the model with app_label.Library, so if the app_label is equal to libraries, then it is:

class SomeModel(models.Model)
    models.ManyToManyField(
        'libraries.Library',
        verbose_name='library choices'
    )

Upvotes: 2

Related Questions