Django 视图是否可以 select 仅针对特定 model.item 的前四个元素?

Django views is it possible to select only the first four elements for a specific 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',如何 return 只有 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 %}