在 Django 的多 table 继承中访问 child 模型 class 属性

Access child model class attributes in multi table inheritance in Django

我正在尝试遍历模板中 child 模型实例的属性,特别是我只想访问 childs 属性。在运行时,我不知道具体 sub-class 是什么。使用 django-model-utils 我已经能够 return sub-class 而不是 parent 这是一个开始,但是当我访问它的属性时,我得到了 parent s and 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)

模板

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

你能做这样的事吗:

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