[Fixed]-Django inheritance obtain typeof child from base class

1👍

Option 1

Add the Meta class with verbose_name to you models:

class Pub(Product):
    product = models.OneToOneField(Product, parent_link=True, )
    seating_capacity = models.IntegerField(null=False, verbose_name="Seating capacity of the Pub",)

    class Meta:
        verbose_name = 'Pub'

class Restaurant(Product):
    product = models.OneToOneField(Product, parent_link=True, )
    food_speciality = MultiSelectField(choices = MY_CHOICES)

    class Meta:
        verbose_name = 'Restaurant'

Add these lines to ProductSerializer:

category = serializers.SerializerMethodField()

def get_category(self, obj):
    return obj._meta.verbose_name

Option 2

Alternatively, you can add a property to each model.

class Pub(Product):
    product = models.OneToOneField(Product, parent_link=True, )
    seating_capacity = models.IntegerField(null=False, verbose_name="Seating capacity of the Pub",)

    @property
    def category(self):
        return 'Pub'

class Restaurant(Product):
    product = models.OneToOneField(Product, parent_link=True, )
    food_speciality = MultiSelectField(choices = MY_CHOICES)

    @property
    def category(self):
        return 'Restaurant'

Then add this line to ProductSerializer:

category = serializers.ReadOnlyField()

Option 3

Of course, you also have the option do this if you don’t want to add Meta or properties to your models:

def get_category(self, obj):
    return obj.__class__.__name__

But then you would have the restriction that every category would be equal to the class’s name, which might be a problem.

Leave a comment