简体   繁体   中英

Access related table field value in django template

I am trying to access a Django related field value in a Django template:

            {% for item in order %}
            <tr>
              
              <td>{{ item.id }}</td>
              <td class="text-left">{{ item.created }}</td>
              <td class="text-left">{{ item.payments__charge_status }}</td>
              <td class="text-left">{{ item.shipping_method_name }}</td>
              <td class="text-right">£{{ item.total_gross_amount }}</td>
              
            </tr>
            {% endfor %}

Actual queryset defined in views.py:

orders = Order.objects.values().filter(created__range=(start_date, end_date)).filter(Q(payments__charge_status="fully-charged") | Q(payments__charge_status="not-charged"))

Payment is in a different table and I can access using payments__charge_status in the view but not in the actual template.

Any help is appreciated.


Updated with models.py for Payment Model:

....

class Payment(models.Model):


    order = models.ForeignKey(
        Order, null=True, related_name="payments", on_delete=models.PROTECT
    )

From your database modeling order can have multiple payments ( Many-to-One )so payments is a QuerySet you should iterate through

{% for payment in item.payments.all %}
          {{ payment.charge_status }   
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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