Django abstract models - how to implement specific access in abstract view method?
<p>Let's say I have an abstract model in Django, with two models extending off that.</p>

<p>Inside a Django Rest Framework generic view, how can I control creation of one of the two implementing models?</p>

<p>My solution is below:</p>

<pre><code>    from enum import Enum
    from rest_framework.views import APIView

    class BazType(Enum):
        FOO = 1
        BAR = 2

    class AbstractView(APIView):
        def __init__self():
            #Init code here

        def _internal_method(self, django_model, this_type = BazType.FOO):
            if this_type == BazType.FOO:
                record, created = ConcreteModelOne.objects.get_or_create(some_field = django_model)
            elif this.type == BazType.BAR:
                record, created = ConcreteModelTwo.objects.get_or_create(some_field = django_model)
</code></pre>

<p>It works, but is there a way to get rid of the if/else block?  In other words, is there a way, from a subclass of <code>AbstractView</code>, to pass in some identifier for which model is required for the <code>get_or_create</code> method call?</p>

<p>You can create a mapping/dictionary that maps a model class to the values of each <code>Enum</code> member, and use it in your <code>_internal_method</code> for fetching the model class given the <code>Enum</code> name:</p>

<pre><code>class AbstractView(APIView):
        models_map = {1: ConcreteModelOne, 2: ConcreteModelTwo}

        def __init__(self):
            #Init code here

        def _internal_method(self, django_model, this_type=BazType.FOO):
            record, created = self.models_map[this_type].objects.get_or_create(some_field = django_model)
</code></pre>

python django