2016-04-08 21 views
0

私は様々なアイテムを表示しているプロファイルモデルを持っています。 その1つはプロフィールに添付されている国です。ここでDjangoビューでは、特定のモデルの最初の4つの要素のみを選択できます。

は、ビューに起こるものです:

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はカテゴリに使用していますが、私がここでしたいものとは関係ありません。

答えて

3

あなたはこのためにsliceフィルタを使用することができます。

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

をあなたがスライスを使用する場合、私は '{%forloop.last%}を呼び出す場合は'それは4番目の要素としてウェルになりますか? –

+0

まあ、(申し訳ありません)! 多くのありがとうAKS :) –

+0

私は助けてうれしいです。あなたの質問を解決するなら、答えを受け入れてください。 – AKS

関連する問題