Hanny
Hanny

Reputation: 2159

Get related items while looping in Django template

I am trying to access a related object (PaymentDetail if it exists) while looping through a _set list of objects (Registrations).

My models look like this:

models

class Registration(models.Model):
    person = models.ForeignKey(Person, on_delete=models.PROTECT)
    course_detail = models.ForeignKey(
        CourseDetail,
        on_delete=models.PROTECT
    )
    comments = models.CharField(max_length=200, blank=True, null=True)

    def __str__(self):
        return '%s' % (self.course_detail.course.name)    

class PaymentDetail(models.Model):
        payment = models.ForeignKey(Payment, on_delete=models.PROTECT)
        registration = models.ForeignKey(
            Registration,
            on_delete=models.PROTECT)

In my views I'm just getting a queryset of desired people and passing it to the template (these display fine).

view

def index(request, **kwargs):
    people = Person.get_related_people(request.user.id).order_by('first_name')
    return render(request, 'people_app/index.html', {
        'people': people,
    })

As I am looping through them in the template - I am displaying the associated Registrations for these people. While I'm looping through those registrations - I'm trying to see if there is a PaymentDetail associated with that Registration

In my template I'm looping through the registration_list like this:

template

{% for person in people %}
    {% for registration in person.registration_set.all %}
        {{ registration.id }} 
        {% if registration.paymentdetail_set|length > 0 %}
            PAID
        {% else %}
            NO PAYMENT
        {% endif %}
    {% endfor %}
{% endfor %}

As you may imagine - this doesn't work and always shows as NO PAYMENT even when the PaymentDetail exists.

Upvotes: 2

Views: 1059

Answers (1)

rollingthedice
rollingthedice

Reputation: 1125

You've missed to type .all() after paymentdetail_set, should look like:

{% if registration.paymentdetail_set.all|length > 0 %}
   PAID
{% else %}
   NO PAYMENT
{% endif %}

Upvotes: 1

Related Questions