[Answered ]-Django: How can I use get_model in my use case to correctly import a class and avoid conflicts

2👍

My guess on get_model() is that running it at the class-definition level can give incorrect results, since it will get evaulated as Django is populating all the models in it’s AppCache. My quick reading of the django.db.models.loading module doesn’t seem to show that issue, but one thing to try is to run get_model() inside a view and print out the results to see if it is what you think it should be, since by that time the AppCache should be fully loaded.

But – as a workaround to get around the original circular import (so you don’t have to use get_model anyway) is to not do the form imports at the module level – you can stick them in the classmethod instead:

class ParentRecord(models.Model):
    @classmethod
    def get_form(self, *args, **kwargs):
        from yourapp.forms import BreathingActivityRecordForm
        return BreathingActivityRecordForm

This way, the import will only be evaulated when you actually call .get_form(), and there shouldn’t be any circular dependencies at module loading tme.

👤AdamKG

Leave a comment