Ilya Bibik
Ilya Bibik

Reputation: 4124

Accessing values from fetched object?

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

I want to list all the discounts I have for certain periods of my lease,query is as follows :

    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"
        )
    )

but when I display the list of periods in my template for the all_discount the output is [<LeaseDiscount: LeaseDiscount object>]

Why? How I access the values of this object? In general am I doing it the right way?

UPDATE: template

          {% for field1 in data.period%}


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

Upvotes: 1

Views: 83

Answers (1)

Prakhar Trivedi
Prakhar Trivedi

Reputation: 8526

As suggested by Daniel,You can iterate through the list given by objects.filter as :

In view:

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

Or in template: Firstly pass the object by render/render_to_response then use something like this:

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

Upvotes: 5

Related Questions