gpt4 book ai didi

python - 将两个查询集组合成一个模板标签

转载 作者:太空宇宙 更新时间:2023-11-03 19:11:23 25 4
gpt4 key购买 nike

我有两个模型 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 %}

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

最佳答案

您想要创建 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 %}

关于python - 将两个查询集组合成一个模板标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12896577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com