嘿,Django回来已经有一个星期了,所以如果这个问题是愚蠢的,请不要介意我,尽管我在stackoverflow和google上搜索了一下,结果没有找到。在
我有一个名为Term的简单模型(尝试为我的新闻模块实现标记和类别),我有一个名为taxonomy_list的模板标记,它应该以逗号分隔的链接列表的形式输出分配给一篇文章的所有术语。现在,我的术语模型没有permalink字段,但是它从我的视图中到达那里并被传递到模板。permalink值在模板中看起来很好,但是没有加载到我的模板标记中。在
为了说明这一点,我从代码中获取了一些信息。下面是我的自定义模板标记taxonomy\u list:
from django import template
from juice.taxonomy.models import Term
from juice.news.models import Post
register = template.Library()
@register.tag
def taxonomy_list(parser, token):
tag_name, terms = token.split_contents()
return TaxonomyNode(terms)
class TaxonomyNode(template.Node):
def __init__(self, terms):
self.terms = template.Variable(terms)
def render(self, context):
terms = self.terms.resolve(context)
links = []
for term in terms.all():
links.append('<a href="%s">%s</a>' % (term.permalink, term.name))
return ", ".join(links)
以下是我的单贴视图:
^{pr2}$这是我在模板中所做的来说明访问类别的两种方法:
Method1: {% taxonomy_list post.categories %}
Method2: {% for c in post.categories %}{{c.slug}} ({{c.permalink}}),{% endfor %}
有趣的是,方法2工作得很好,但是方法1说明我的.permalink字段是未定义的,这可能意味着变量解析没有按照我的预期完成,因为“额外的”permalink字段被忽略了。在
我想可能变量没有识别字段,因为它没有在模型中定义,所以我尝试在模型中给它分配一个“临时”值,但这也没有帮助。Method1在链接中包含“temporary”,而method2运行正常。在
有什么想法吗?在
谢谢!在
这其实不是一个可变分辨率的问题。问题是如何从Post对象获取术语。在
当在模板标记中执行
for term in terms.all()
操作时,all
会告诉Django重新计算queryset,这意味着再次查询数据库。因此,您仔细注释过的术语将被数据库中的新对象刷新,permalink
属性将被覆盖。在如果您只需删除
all
,它可能会起作用,所以您只需要for term in terms:
。这将重用现有对象。在相关问题 更多 >
编程相关推荐