0

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

视图.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 %}
4

1 回答 1

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
于 2017-02-21T15:44:52.873 回答