繁体   English   中英

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

[英]Access child model class attributes in multi table inheritance in Django

我试图遍历模板中子模型实例的属性,特别是我只想访问子属性。 在运行时,我不知道它是什么具体的子类。 使用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 %}

你能做这样的事情:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM