0

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 %}
KingFu
  • 1,358
  • 5
  • 22
  • 42
  • Isn't that how it should be? A child inherits the parent's attributes, so it's normal that `Product` attributes such as `created_at` are also shown, no? – Mathieu Dhondt Feb 21 '17 at 15:25
  • @LaundroMat I assume so, but I'm trying to find a way of returning only the child's attributes if this is possible – KingFu Feb 21 '17 at 15:35
  • 1
    Oh ok then :) Maybe this answer can put you on your way? http://stackoverflow.com/questions/7136154/python-how-to-get-subclasss-new-attributes-name-in-base-classs-method – Mathieu Dhondt Feb 21 '17 at 15:41
  • @LaundroMatthanks that's helped,` __class__` is the secret sauce I'm missing – KingFu Feb 21 '17 at 15:51

1 Answers1

1

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
Nasef Khan
  • 222
  • 1
  • 5