[Answered ]-How to access related model in Django custom model manager?

1👍

So, I went old school and did this to make it work,

data = validated_data.pop(kind)
act = self.create(**validated_data)
if act.kind == 'A':
    from activity.models import ActivityA  # Prevent the circular import
    ActivityA.objects.create(activity=act, **data)
elif act.kind == 'B':
    from activity.models import ActivityB
    ActivityB.objects.create(activity=act, **data)

It works, but doesn’t look clean. Any better solution other?


Update:

So, using django.apps.apps.get_model is the answer. Thanks @djvj for pointing me in the right direction.
Doc says that:

apps.get_model(app_label, model_name, require_ready=True)
Returns the Model with the given app_label and model_name. As a shortcut, this method also accepts a single argument in the form app_label.model_name. model_name is case-insensitive.

Example:

from django.apps import apps

class ActivityManager(models.Manager):
def create_activity(self, validated_data):
    # ...

    data = validated_data.pop(kind)
    act = self.create(**validated_data)
    if act.kind == 'A':
        model = apps.get_model(app_label='activity', model_name='ActivityA')
        model.objects.create(activity=act, **data)
    elif act.kind == 'B':
        model = apps.get_model(app_label='activity', model_name='ActivityB')
        model.objects.create(activity=act, **data)

     # ... 
# ... 

apps.get_model(app_label='activity', model_name='ActivityA') can be simply written as

apps.get_model('activity.ActivityA')
👤haccks

Leave a comment