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 %}
4
  • 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? Commented Feb 21, 2017 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 Commented Feb 21, 2017 at 15:35
  • 1
    Oh ok then :) Maybe this answer can put you on your way? stackoverflow.com/questions/7136154/… Commented Feb 21, 2017 at 15:41
  • @LaundroMatthanks that's helped,` __class__` is the secret sauce I'm missing Commented Feb 21, 2017 at 15:51

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks this works, you're missing an _ after "_class" though.
No problem, fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.