简体   繁体   中英

Filtering Results Using `get_context_data` in a ListView

In my ListView, I want to return the entire list of objects from my Publication model and return the total from my Budget model to include in the ListView with each title and the associated total.

My Models:

Publication App

class Publication(models.Model):
      title = models.CharField(...)

Budget App

class Budget(models.Model):
      total = models.DecimalField(...)
      publication = models.ForeignKey(Publication, ...)

Views: Publication App

class PublicationListView(ListView):
      context_object_name = 'publications'
      model = Publication

      def get_context_data(self, **kwargs):
          context = super(PublicationListView, self).get_context_data(**kwargs)

          context['publication'] = self.get_queryset()
          context['budget'] = Budget.objects.all()

          return context

Template: Publication App

<tbody>
   {% for pub in publications %}
    <tr>
        <td><a href="{{ pub.pk }}">{{ pub.title }}</a>
            <span class="float-right">
                 {% for obj in budget %}
                     {{obj}}
                 {% endfor %}
            </span>
        </td>
    </tr>
   {% endfor %}
</tbody>

In my template, the results I am receiving look something like this:

publication 1               1000 2000 3000
publication 2               1000 2000 3000
publication 3               1000 2000 3000

But what I need is:

publication 1               1000
publication 2               2000
publication 3               3000

I understand why I am returning all budget objects in each row, but I am not sure how to only display the correct budget with the associated publication.

Is using get_context_data() the best option for this?

Thanks to the direction of @HakenLid and @WillemVanOnsem, below are the updated view and template to achieve the desired output

View

class PublicationListView(ListView):
      context_object_name = 'publications'
      model = Publication

Template

<tbody>
   {% for pub in publications %}
    <tr>
        <td><a href="{{ pub.pk }}">{{ pub.title }}</a>
            <span class="float-right">
                 {% for budget in pub.budget_set.all %}
                     {{ budget }}
                 {% endfor %}
            </span>
        </td>
    </tr>
   {% endfor %}
</tbody>

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