从获取的对象访问值?

时间:2016-10-05 11:52:35

标签: django

models.py

class Period(CommonInfo):
    order_value = models.PositiveSmallIntegerField()
    start_date = models.DateField()
    end_date = models.DateField()
    name = models.CharField(max_length=30)

class LeaseDiscount(CommonInfo):
    amount  = models.DecimalField(max_digits=7, decimal_places=2)
    amountpayed = models.DecimalField(max_digits=7, decimal_places=2)
    leaseterm = models.ForeignKey(LeaseTerm)
    period_date = models.ForeignKey(Period)

views.py

我想列出我租约的某些期间的所有折扣,查询如下:

    period = Period.objects.filter(order_value__gte = start, order_value__lte = end).prefetch_related(
        Prefetch(
            "leasediscount_set",
            queryset=LeaseDiscount.objects.filter(is_active=True, leaseterm =  activeterm),
            to_attr="all_discount"
        )
    )

但是当我在模板中显示all_discount的句点列表时,输出为[<LeaseDiscount: LeaseDiscount object>]

为什么呢?我如何访问此对象的值?总的来说,我是以正确的方式做到的吗?

更新: 模板

          {% for field1 in data.period%}


                    <td> {{ field1.all_discount }}</td>

1 个答案:

答案 0 :(得分:5)

根据Daniel的建议,您可以遍历objects.filter给出的列表:

在视图中:

    for data in period:  # period is a LeaseDiscount object
        print data.some_field_name   # LeaseDiscount model fields

或在模板中:      首先通过render / render_to_response传递对象,然后使用类似这样的东西:

 {% for data in period %}
   {{ data.some_field_name }}
 {% endfor %}