Search code examples
djangodjango-modelsdropdown

How would I add a dropdown box that contains all the different type of models in my program?


I want a drop down box of all the models in my program.

I made a myModels model that has a charfield of 100. I tried to add the choice tuple and then reference it in the model.

    helper_choices = []
    for my_model in django.apps.apps.get_models():
        helper_choices.append((my_model._meta.verbose_name, my_model._meta.verbose_name))
    MODEL_CHOICES = tuple(helper_choices)
    model_name = models.CharField(max_length=100, choices=MODEL_CHOICES, default='')

However since this is occurring during the loading of the models phase, I get an error "Models aren't loaded yet." What would be a workaround to this problem?


Solution

  • It is indeed impossible to call django.apps.apps.get_models() from the top-level of a models module, since the model's registry is currently being populated. This would create an infine recursion.

    Also, choices defined at the model level are freezed in migrations, so everytime your models list changes you'd need a migration.

    And finally, you may want to handle the case of "legacy" models - if you remove a model from your project, records pointing to it won't validate anymore.

    I also note that you start your question with

    I want a drop down box of all the models in my program.

    So it looks it's more for UI purpose ?

    Anyway: the simple solution is to leave the choices argument out of your models and only specify it in the form where you need this models selection. You may also want to use the canonical app_label.model_name as effective value and only use the verbose name for display (unless you don't care about having unusable data, that is).