将两个查询集合并到模板标记中

时间:2012-10-15 13:24:59

标签: python django django-templates

我有两个模型news.article和portfolio.entry。两个模型都有一个BooleanField,用于将“is_campaign”设置为true。

我正在尝试编写自定义模板标签,以便获取最新的广告系列文章(应该只有一个)

以下是我的模板标签:campaign_article.py

from itertools import chain
from django import template

from news.models import Article
from portfolio.models import Entry

register = template.Library()

def get_campaign():
        #Get the newest news article with is_campaign=True
        article = Article.objects.filter(is_campaign=True).order_by('-pub_date')[:1]

        #Get the newest portfolio entry with is_campaign=True
        portfolio = Portfolio_entry.objects.filter(is_campaign=True).order_by('-pub_date')[:1]

        #combine article, and entry and display only the newest
        campaign_article = list(chain(article, portfolio))[:1]


        return {'campaign_article': campaign_article}



register.tag('campaign', get_campaign)

我在我的模板中试过这个:

{% load campaign_article %}
{% for campaign_article in campaign %}

{{ campaign_article.id }}

{% endfor %}

但我没有得到任何输出。这是错误的方法吗?

2 个答案:

答案 0 :(得分:1)

您可能希望创建assignment_tag而不是通用标记。 因此,您可以将标记更新为:

def get_campaign():
    #your stuff
    ....

    return campaign_article

register.assignment_tag(get_campaign, name='campaign')

将模板更新为:

{% load campaign_article %}
{% campaign as campaign_list %} {# loads the tags and creates campaign_list context variable #}
{% for campaign_article in campaign_list %}
    {{ campaign_article.id }}
{% endfor %}

答案 1 :(得分:0)

您无需创建模板标记即可执行所需操作。阅读context processor

def get_campaign(request): # this is your context processor            
        # ...    
        return {'campaign_article': campaign_article}

在您看来:

def some_view(request):
    # ...
    c = RequestContext(request, {
        'foo': 'bar',
    }, [get_campaign]) # attach your context processor to template context
    return HttpResponse(t.render(c))

UPD:如果您需要在每个页面上显示数据,可以在设置文件中将上下文处理器注册为全局。请参阅template context processors设置。

TEMPLATE_CONTEXT_PROCESSORS = (..., "myapp.context_processors.get_campaign")

Django会自动为每个模板渲染添加变量campaign_article