在Django中访问多表继承中的子模型类属性

时间:2017-02-21 15:09:06

标签: python django django-model-utils

我正在尝试在模板中迭代子模型实例的属性,特别是我只想访问子属性。在运行时我不知道它是什么具体的子类。使用django-model-utils我已经能够返回子类而不是父类,这是一个开始,但是当我访问它的属性时,我得到了父项返回的子项:

    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 %}

1 个答案:

答案 0 :(得分:1)

你能做这样的事吗:

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