2016-04-08 17 views
0

我有一個顯示各種項目的配置文件模型。 其中之一是國家連接到配置文件。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_list,industry_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%}'這將是第四個元素爲井? –

+0

好吧,(抱歉)! 非常感謝AKS :) –

+0

我很樂意提供幫助。請接受答案,如果它解決您的查詢。 – AKS

相關問題