Access child model class attributes in multi table inheritance in Django

1k Views Asked by At

I'm trying to iterate over a child model instances' attributes in a template, specifically I only want to access the childs attributes. At runtime I won't know what concrete sub-class it is. Using django-model-utils I've been able to return the sub-class instead the parent which is a start, but when I access its attributes I get both the parents and the childs returned:

    class Product(models.Model):
        created_at      = models.DateTimeField(default=timezone.now)
        updated_at      = models.DateTimeField(auto_now=True)
        name            = models.CharField(...)
        objects = InheritanceManager()

        def attrs(self):
            for attr, value in self.__dict__.iteritems():
                yield attr, value

    class Vacuum(Product):
        power           = models.DecimalField(...)

    class Toaster(Product):
        weight           = models.DecimalField(...)

views.py

def product_detail(request, slug):
    product = Product.objects.get_subclass(slug=slug)

template

{% for name, value in product.attrs %}
          <td>{{ name }}</td>
          <td>{{ value }}</td>
{% endfor %}
1

There are 1 best solutions below

2
On BEST ANSWER

Can you do something like this:

def product_detail(request, slug):
    product = Product.objects.get_subclass(slug=slug)
    child_fields = [i for i in product.__class__.__dict__ if 
                    not i.startswith("__") and not hasattr(Product, i)]
    product_attrs = [(name, getattr(product,name)) for name in child_fields]
    # pass product_attrs to your template