Good day everyone, hope you’re doing really well.
Straight to the point, let’s say we have an app with some models:
from django.apps import apps from django.db import models class A(models.Model): # A lot of fields go here class B(models.Model): # A lot of fields go here # And some more models ... class ModelChoices(models.TextChoices): A = 'A' B = 'B' ... class Filterset(models.Model): model = models.CharField(max_length=32, choices=ModelChoices.choices) attribute = models.CharField(max_length=32, choices=auto_generate_attributes().choices) def auto_generate_attributes(): all_attributes = set() for model_name in ModelChoices.values: ModelClass = apps.get_model(model_name) model_fields = ModelClass._meta.get_fields() model_attributes = [(attr.name, attr.name) for attr in model_fields] all_attributes.update(model_attributes), Attributes = models.TextChoices( 'Attributes', list(all_attributes), ) return Attributes
Now you’re probably wondering what’s the point of this table. In short, I’ll use it in a M2M relationship with another model so that an User can filter on values of different models at once and return a list of FK objects that all models share (Sounds abstract, but trust me). But the other models are still a work in progress and will edit/create new fields as time goes, that’s why I have to generate them dynamically instead of hard-coding them.
The issue is trying to get the models classes at initilization time to popuplate the choices of the
Filterset model, because Django returns this error:
# ...Rest of the tracestack goes here... ModelClass = apps.get_model(model_name) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 19 8, in get_model self.check_models_ready() File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 14 0, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
I’ve tried many of the solutions proposed in other forums of the same nature:
- Importing the models explicitly instead of using
get_model, returns the same error.
- Using import
django.setup()at the top of the file, returns
RuntimeError: populate() isnt reentrant, which doesn’t say much.
- Creating the attributes list in another file outside of models, returns the same error whenever you call the function.
I’ve seen people try to overwrite the
ready() method of the
AppConfig class for the app, but don’t know how to translate that into my specific problem. Is there really a way to have this successfully generate the fields at initialization and create the migration with all choices?
Thank you in advance for any help you may have. I’ve thoroughly searched the internet but no luck still, so I feel as helpless as I can be.