Django视图可以只为特定的model.item选择前四个元素



我有一个显示各种项目的概要文件模型。其中之一是个人资料所附的国家。

以下是视图中发生的情况:

class ProfilePartnerListView(FormMixin, BaseProfilePartnerView, ListView):
    model = ProfilePartner
    context_object_name = 'profile_list'
    view_url_name = 'djangocms_partner_profile:profile-list'
    def get(self, request, *args, **kwargs):
      context = {}
      self.object_list = self.get_queryset().order_by('-date_created')
      context.update(self.get_context_data(**kwargs))
      context[self.context_object_name] = context['object_list']
      country_for_articles = Country.objects.exclude(regions_partner_profile=None).order_by('name')
      industries_qs = ProfilePartnerIndustry.objects.active_translations(
        get_language()).order_by('translations__name')
      budget_qs = ProfilePartner.objects.values_list('budget',
                                                        flat=True).distinct()
      context['load_more_url'] = self.get_load_more_url(request, context)

      context['regions_list'] = country_for_articles
      context['industry_list'] = industries_qs
      context['budget_list'] = budget_qs
      return self.render_to_response(context)

我知道,例如"regions_list",如何从中只返回4个元素。但问题是,我在渲染模板中使用的主要对象"profile_list"显示了项目的所有国家/地区:

{% for profile in profile_list %}
    {% for country in profile.regions.all %}
        <div class="col-xs-12">{{ country }}</div>
    {% endfor %}
{% endfor %}

一些个人资料得到了5或6个国家。我只想显示前4个。有办法做到这一点吗?

非常感谢!

ps:region_listindustry_listbudget_list用于类别,与我在这里想要什么无关。

您可以为此使用slice过滤器:

{% for profile in profile_list %}
    {% for country in profile.regions.all|slice:":4" %}
        <div class="col-xs-12">{{ country }}</div>
    {% endfor %}
{% endfor %}

最新更新